[Leetcode]231. Power of Two

来源:互联网 发布:广州少儿编程培训机构 编辑:程序博客网 时间:2024/06/18 06:37

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

麻烦一点的话,用循环来判断。

class Solution {public:    bool isPowerOfTwo(int n) {        if(n<=0)            return false;        while(n){            if(n%2!=0){                if(n==1)                    return true;                else                    return false;            }            else                n/=2;        }        return true;    }};
这里有个简单方法,如果n是2的幂,则n的二进制表示形式中只有1个1,通过移位,从N&(N-1)来判断。

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

0 0