This is kind of cheating, but the idea is that a power of two in binary form has and only has one "1".
public class Solution {
public boolean isPowerOfTwo(int n) {
return n>0 && Integer.bitCount(n) == 1;
}
}
Same idea here. Count the number of ones (should be 1) by right shifting n by 32 times (be sure to kick out 0x80000000).
public boolean isPowerOfTwo(int n) {
if (n == 0x80000000) return false;
int ones = 0;
for (int i = 1; i <= 32; ++i) {
ones += n & 1;
n = n >> 1;
}
return ones == 1;
}