Hi community,

Came across a simple piece of code to check if a given no is a power of 2. Thought of sharing it here , many may be aware of this though.

Method- 1

Suppose we have a no n and we want to check if its a power of 2.

```
if(!(n&n-1==0)) printf("power of zero!!!");
Explanation:
suppose n=8 (1000 in binary) then n-1=7 (0111);
1000
& 0111
= 0
if n=6
110
& 101
= 100
```

Method 2:

Assuming n>0

```
if ((n & -n) == n) {
// n is a power of two
```

}

Edit- Have added Method 2 to check for it.

Edit 2- Some of the other methods for checking this can be found here. pow of 2

Edit 3- For detailed implementation check this link link text

Hope this helps. Happy coding …