# One line java solution using bitCount

• 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;
}
}``````

• This post is deleted!

• ``````public boolean isPowerOfTwo(int n) {

if(n<=0)
return false;
int log_base_2= (int)(Math.log(n)/Math.log(2));
return (((n & (1<< log_base_2)) ==n)?true:false);

}
``````

I used shift operator !

• 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;
}
``````

• @qxx I have the same, but this is actually not efficient =(

• ``````public static boolean isPowerOfTwo(int n) {
return n > 0 && Integer.highestOneBit(n) == Integer.lowestOneBit(n) ? true : false;
}
``````

This is my solution. so easy to understand.

• What is the runtime complexity of Integer.bitCount()? Is it O(n) where n is the number of bits of the integer?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.