Leetcode 231. Power of Two

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/82390207

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Power of Two

2. Solution

  • Version 1
class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n == 0) {
            return false;
        }
        while(n != 1) {
            if(n % 2) {
               return false; 
            }
            n /= 2;
        }
        return true;
    }
};
  • Version 2
class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n == 0) {
            return false;
        }
        while(n != 1) {
            if(n % 2) {
               return false; 
            }
            n >>= 1;
        }
        return true;
    }
};
  • Version 3
class Solution {
public:
    bool isPowerOfTwo(int n) {
        return n > 0 && !(n & (n - 1));
    }
};

Reference

  1. https://leetcode.com/problems/power-of-two/description/

猜你喜欢

转载自blog.csdn.net/Quincuntial/article/details/82390207