lintcode-easy-O(1) Check Power of 2

Using O(1) time to check whether an integer n is a power of 2.

For n=4, return true;

For n=5, return false;

 

这道题就是看一下这个int二进制各位上总共是否只有一个1,如果只有一个1则是2的n次方。但是要注意特殊情况,如果这个数是Integer.MIN_VALUE,也只有一位是1,但是这个数是负数,所以不是2的n次方。

class Solution {
    /*
     * @param n: An integer
     * @return: True or false
     */
    public boolean checkPowerOf2(int n) {
        // write your code here
        int count = 0;
        
        if(n == Integer.MIN_VALUE)
            return false;
        
        for(int i = 0; i < 32; i++){
            if(((n >> i) & 1) == 1)
                count++;
        }
        
        return count == 1;
    }
};

 

posted @ 2016-03-03 07:49  哥布林工程师  阅读(112)  评论(0编辑  收藏  举报