LeetCode 231 Power of Two

来源:互联网 发布:上座部佛教 知乎 编辑:程序博客网 时间:2024/06/03 15:44

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

AC代码如下:

class Solution {public:    bool isPowerOfTwo(int n) {        if(n<=0)            return false;        int count=0;        for(int i=0;i<sizeof(int)*8;i++){            if(n>>i&1==1)                count++;            if(count>=2)                return false;        }        return true;    }};
看了大牛的解答,后自愧不如,代码如下:

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



0 0
原创粉丝点击