首页 > 其他 > 详细

O(1) Check Power of 2

时间:2016-07-19 13:12:57      阅读:216      评论:0      收藏:0      [点我收藏+]

Note:
1) * 2 is same as << 1, so the number contains only one bit that is 1, the rest of bits are 0. 
2) n-1 sets all the bits after bit 1 from 0 to 1, and bit 1 to from 1 to 0
3) (n & (n-1)) always equal to 0 when n is power of 2
4) eg. 8(1000) &7(0111), 4(0100) &3(0011)
5) when n = 0, it suppose to return false, but it will return true.

class Solution {
public:
    /*
     * @param n: An integer
     * @return: True or false
     */
    bool checkPowerOf2(int n) {
        // write your code here
        return n > 0 && (n & (n - 1)) == 0;
    }
};

Here is a O(n) way:

class Solution {
public:
    /*
     * @param n: An integer
     * @return: True or false
     */
    bool checkPowerOf2(int n) {
        // write your code here
        int calculation = 0;
        for (int exp = 1; calculation < n; ++exp){
            calculation << 1;
            if (calculation == n){
                return true;
            }
        } 
        return false;
    }
};

 

O(1) Check Power of 2

原文:http://www.cnblogs.com/codingEskimo/p/5684163.html

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