How to check if a number is power of 2

How to check if a number is power of 2 in bitwise? Can you tell me how to do it with a little explanation.

See this you will get an hint

I know there is to be only 1 set bit. Is that it? I saw some other code for checking if a power of 2, couldn’t understand. Can you share your approach/ code for this.

As for the question, cause it’s only asking number of set bits in a number, and we are doing it in log2(N) time complexity

If you want to check if and only if a number is a power of 2, what you can do is

N&(N-1)==0, then it's a power of 2
for eg:
     N = 4 & N-1 = 3
so,   (100) & (011) = 000
this is done in O(1) time

For this problem, it’s same as you have submitted your code for this problem
You can see the logic here too

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

1 Like