Chinaunix
标题: 如何判断一个整数是不是2的N次幂 [打印本页]
作者: loki67 时间: 2011-12-21 08:41
标题: 如何判断一个整数是不是2的N次幂
简单来讲,如果X为2的N次幂,则(X&(X-1)) == 0成立。
*************************************************
The binary representation of integers makes it possible to apply a very fast test to determine whether a given positive integer x is a power of two:
x is a power of two \Leftrightarrow (x & (x − 1)) equals zero.
where & is a bitwise logical AND operator.
Examples:
−1 = 1...111...1
−1 = 1...111...111...1
x = 0...010...0
y = 0...010...010...0
x−1 = 0...001...1
y−1 = 0...010...001...1
x & (x−1) = 0...000...0
y & (y−1) = 0...010...000...0
Note that zero is incorrectly considered a power of two by this test.
欢迎光临 Chinaunix (http://bbs.chinaunix.net/) |
Powered by Discuz! X3.2 |