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 && __builtin_popcount(n) == 1;
  }
};
1
2
3
4
5
class Solution {
  public boolean isPowerOfTwo(int n) {
    return n >= 0 && Integer.bitCount(n) == 1;
  }
}
1
2
3
class Solution:
  def isPowerOfTwo(self, n: int) -> bool:
    return n >= 0 and n.bit_count() == 1