What do (n&(n-1))==0 and n&(n-1)==0 do in C++?

為{幸葍}努か 提交于 2021-02-06 14:19:31

问题


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 1s.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!