首页 > 其他 > 详细

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

时间:2016-03-03 07:56:24      阅读:227      评论:0      收藏:0      [点我收藏+]

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

 

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

原文:http://www.cnblogs.com/goblinengineer/p/5237184.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!