[Title]
Given an integer, write a function to determine whether it is a power of 2.
[Example 1]
Input: 1
Output: true
Explanation: 20 = 1
[Example 2]
Input: 16
Output: true
Explanation: 24 = 16
[Example 3]
Input: 218
Output: false
[Code]
[Python]
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n&(n-1)==0 and n!=0
[Method 2]
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
dic=dict(Counter(bin(n)[2:]))
return dic.setdefault('1',0)==1 and n>=0
[Method 3: Digital Method]
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n<=0:
return False
while n>1:
if n%2:
return False
n//=2
return True