LeetCode Solutions

231. Power of Two

Time: $O(1)$

Space: $O(1)$

			

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

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

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