231. Power of Two

Power of Two - LeetCode

Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2x.

Example 1: Input: n = 1 Output: true Explanation: 20 = 1 Example 2: Input: n = 16 Output: true Explanation: 24 = 16 Example 3: Input: n = 3 Output: false

Constraints: -231 <= n <= 231 - 1


  • code
class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        while n > 1:
            if n % 2 != 0: return False
            n = n // 2
        return n == 1

power of 2 a power of two in binary representation is one 1-bit, followed by some zeros: 1 = (0000 0001)_21=(00000001)2​
2 = (0000 0010)_22=(00000010)2​
4 = (0000 0100)_24=(00000100)2​
8 = (0000 1000)_28=(00001000)2​
A number which is not a power of two, has more than one 1-bit in its binary representation: 3 = (0000 0011)_23=(00000011)2​
5 = (0000 0101)_25=(00000101)2​
6 = (0000 0110)_26=(00000110)2​
7 = (0000 0111)_27=(00000111)2​
The only exception is 0, which should be treated separately.

fig fig

  • code
class Solution(object):
    def isPowerOfTwo(self, n):
        if n == 0:
            return False
        return n & (-n) == n
  • code
class Solution {
  public boolean isPowerOfTwo(int n) {
    if (n == 0) return false;
    long x = (long) n;
    return (x & (-x)) == x;
  }
}