码迷,mamicode.com
首页 > 其他好文 > 详细

O(1) Check Power of 2

时间:2016-07-19 13:14:32      阅读:188      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!