ling - 6 months ago 34

Java Question

Isn't this one way to test whether a number is a power of 2?

`boolean isPowerOfTwo(int n) {`

return (n%2==0);

}

Answer

Are you sure that you are checking power of 2? Rather, being checked divisible with 2. If you are serious, use the piece of cake snippet

```
return ((n & -n) == n)
```

The second way,

```
private static boolean powerOf2(int num)
{
if(num <= 0){
return false;
}
while(num > 1)
{
if(num % 2 != 0)
{
return false;
}
num = num / 2;
}
return true;
}
```