Sunday, September 13, 2015

Power of Two

Given an integer, write a function to determine if it is a power of two.
Solution1: 向右移1位 = n / 2
public class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n == 1) {
            return true;
        }
        
        int temp = n;
        while (temp != 2) {
            if (temp % 2 != 0 || temp < 2) {
                return false;
            }
            temp = temp >> 1;
        }
        
        return true;
    }
}
Solution2: Better solution
如果一个整数是2的幂,那么它的二进制形式最高位为1,其余各位为0
等价于:n & (n - 1) = 0,且n > 0
public class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n > 0 && (n & (n - 1)) == 0) {
            return true;
        }
        
        return false;
    }
}

No comments:

Post a Comment