Leetcode

Power of Two

  • Time:O(1)
  • Space:O(1)

C++

class Solution {
 public:
  bool isPowerOfTwo(int n) {
    return n < 0 ? false : __builtin_popcountll(n) == 1;
  }
};

JAVA

class Solution {
  public boolean isPowerOfTwo(int n) {
    return n < 0 ? false : Integer.bitCount(n) == 1;
  }
}

Python

class Solution:
  def isPowerOfTwo(self, n: int) -> bool:
    return False if n < 0 else bin(n).count('1') == 1