简单来讲,如果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.
阅读(1754) | 评论(0) | 转发(0) |