leetcode 231:2的幂

题目:

算法思想:一个数是2的幂,那么二进制形式一定是100000这种形式,那么n&n-1一定是0,否则就不是2的幂,注意输入n可能小于等于0,需要做判断。

代码:

    bool isPowerOfTwo(int n) {
        if(n <= 0)
            return false;
        if( ( n & (n - 1) ) == 0  )
            return true;
        return false;
    }
发布了137 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/wh_computers/article/details/100533326