LeetCode: Power of Two

LeetCode: Power of Two

Given an integer, write a function to determine if it is a power of two.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class PowerOfTwo {
public boolean isPowerOfTwo(int n) {
int count = 0;
if(n < 1) {
return false;
}
for(int i = 0;i<32;i++) {
if((n & 1) != 0) {
count++;
}
if(count > 1) {
return false;
}
n = n >> 1;
}

return count == 1;
}
}