Leetcode 231. Power of Two

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

1. Description

《Leetcode 231. Power of Two》 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/
    原文作者:SnailTyan
    原文地址: https://www.jianshu.com/p/d05cd45e0615
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞