Skip to content

231. Power of Two 👍

  • Time: $O(1)$
  • Space: $O(1)$
1
2
3
4
5
6
class Solution {
 public:
  bool isPowerOfTwo(int n) {
    return n < 0 ? false : __builtin_popcountll(n) == 1;
  }
};
1
2
3
4
5
class Solution {
  public boolean isPowerOfTwo(int n) {
    return n < 0 ? false : Integer.bitCount(n) == 1;
  }
}
1
2
3
class Solution:
  def isPowerOfTwo(self, n: int) -> bool:
    return False if n < 0 else bin(n).count('1') == 1