Given an integer, write a function to determine if it is a power of two.
My solution:
public class Solution {
public boolean isPowerOfTwo(int n) {
if(n<1)
return false;
if((n&(n-1))==0)
return true;
else
return false;
}
}
Or use Integer.bitCount.
public class Solution {
public boolean isPowerOfTwo(int n) {
return n>0&&Integer.bitCount(n)==1;
}
}