问题
What do (n&(n-1))==0
and n&(n-1)==0
do (n
is an integer) in C++?
if ((n&(n-1))==0)
{
// do something
}
if (n&(n-1)==0)
{
// do something
}
回答1:
(n & (n - 1)) == 0
:
n & (n - 1)
unset the lower set bit of n
in binary: XXX10000
-> XXX00000
So (n & (n - 1)) == 0
for 0
and all powers of 2
.
n & (n - 1) == 0
:
n & (n - 1) == 0
is equivalent to n & ((n - 1) == 0)
(due to precedence of operator) and so n == 1
.
回答2:
They are suppose to test if the number n
is a power of 2 (although the second one fails to do so as mentioned in the comment). It is based on a simple observation that in binary representation powers of 2 are the only numbers with just one bit set to 1
. If you subtract 1
from such number you get a sequence of 1
s.
Example (positive):
n = 32
than in binary representation
n = 100000
Then
n - 1 = 011111
So if you take n - 1 & n
you get 0
.
Example (negative):
n = 6
than in binary representation
n = 110
Now
n - 1 = 101
So ((n - 1) & n) == 100 > 0
.
Note, that, as @harold mentioned in his comment, 0
will also pass this test.
回答3:
As Lukaszz Said,
it checks whether number n is power of two or not.
Explanation :-
if n = 3 or any other number which is not power of 2
(n = 3, So (n-1) = 2)
3 :- 0000 0011 2 :- 0000 0010
than AND operation :- 0000 0010
if n = 2 or any other number which is power of two
(n = 2 so (n-1) = 1) 2 :- 0000 0010 1 :- 0000 0001
than AND Operation :- 0000 0000
So if the number is power of two it always returns 0.
回答4:
It is used to check for the power of two as follows ::
bool isPowerOfTwo(int n) {
return!(n&n-1)*n>0;
}
来源:https://stackoverflow.com/questions/21234217/what-do-nn-1-0-and-nn-1-0-do-in-c