leetcode 231 Power of Two(位运算)

Given an integer, write a function to determine if it is a power of two.

题解:一次一次除2来做的话,效率低。所以使用位运算的方法(左移一位相当于原数乘2)列出在int范围内的所有2的倍数,然后和n异或如果等于0,那么n就是它(两个数的异或为0,那么两个数就相等)。

注意:位运算的优先级比==的优先级低,要加括弧。

class Solution {
public:
    bool isPowerOfTwo(int n) {
        int a=1;
        if(n<=0){
            return false;
        }
        else{
            for(int i=1;i<=31;i++){
                if((n^a)==0){
                    return true;
                }
                else{
                    a<<=1;
                }
            }
            return false;
        }
    }
};

 更好的解法:一个数是2的倍数,那么它的二进制表示中只有一个1,其它都是0,所以如果n&(n-1)==0,那么n就是2的倍数(因为减1只会影响二进制表示中最靠右的1).

class Solution {
public:
    bool isPowerOfTwo(int n) {
        return (n>0)&&((n&(n-1))==0);
    }
};

 

posted @ 2016-02-25 15:47  周洋  阅读(265)  评论(0编辑  收藏  举报