美文网首页Leetcode
Leetcode 231. Power of Two

Leetcode 231. Power of Two

作者: SnailTyan | 来源:发表于2018-09-04 20:56 被阅读2次

文章作者: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/

相关文章

网友评论

    本文标题:Leetcode 231. Power of Two

    本文链接:https://www.haomeiwen.com/subject/blvnwftx.html