Power of Two
Question
Given an integer, write a function to determine if it is a power of two.
Tags
- Mathematics
Thought
Two solutions
- while loop
- binary number
For the first one, we can use a while loop to divide the number by 2 until it cannot be divided by 2.
For the second one, we can count the number of 1
in the corresponding binary number. If the number is exactly 1, then it is the pow of 2.
Code
while loop
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
num = n
while num > 1:
if num % 2 != 0:
return False
else:
num /= 2
if num == 1:
return True
else:
return False
binary number
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False
num = bin(n).count('1')
return num == 1