You are 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 == (2^x).
Example 1:
Input: n = 1
Output: trueExplanation: (2^0) is 1.
Example 2:
Input: n = 8
Output: trueExplanation: (2^3) is 8.
Example 3:
Input: n = 12
Output: falseConstraints:
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n <= 0:
return False
x = 1
while x < n:
x *= 2
return x == nclass Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 1:
return True
if n <= 0 or n % 2 == 1:
return False
return self.isPowerOfTwo(n // 2)class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n <= 0:
return False
while n % 2 == 0:
n >>= 1
return n == 1class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (-n)) == nclass Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and ((1 << 30) % n) == 0