231. Power of Two
Given an integer, write a function to determine if it is a power of two.
解法一
public class Solution {
public boolean isPowerOfTwo(int n) {
if (n <= 0) return false;
return (n & (n - 1)) == 0;
}
}
解法二
public class Solution {
public boolean isPowerOfTwo(int n) {
return n>0 && Integer.bitCount(n) == 1;
}
}
解法三
public class Solution {
public boolean isPowerOfTwo(int n) {
return n>0 && (n==1 || (n%2==0 && isPowerOfTwo(n/2)));
}
}