231. 2的幂

题目分析:
除了特殊数字1之外,凡是2的幂的整数,在整除2的时候余数都为0,并且一直除以2最后总能得到商是1。
此外还需要注意0这个情况。

//C++
class Solution {
public:
    bool isPowerOfTwo(int n) {
        while(n >= 2 && n % 2 == 0){
            n >>= 1;
        }
        return n == 1;
    }
};
class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n == 0){
            return false;
        }
        while(n % 2 == 0){
            n >>= 1;
        }
        return n == 1;
    }
};

猜你喜欢

转载自blog.csdn.net/LITTENg/article/details/80735335