PROBLEM DESCRIPTION
Given a non-negative integer n. The task is to check if it is a power of 2.
SOLUTION
The number of set bits should be 1.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public static boolean isPowerofTwo(long n) {
int c = 0;
while( n != 0 ){
if( (n&1) != 0 ){
c++;
}
n = n >> 1;
if(c > 1)
return false;
}
return c == 1;
}
}