Skip to main content

342. Power of Four

https://leetcode.com/problems/power-of-four/

Python

Straight forward solution

class Solution:
def isPowerOfFour(self, n: int) -> bool:
for i in range(16):
if n == 4**i:
return True
return False

Math

from math import log2


class Solution:
def isPowerOfFour(self, n: int) -> bool:
if n <= 0:
return False
return log2(n) % 2 == 0

Bit Manipulation

class Solution:
def isPowerOfFour(self, n: int) -> bool:
if n <= 0:
return False

if n & (n-1) != 0:
return False

# 2^32
return n & 0b10101010101010101010101010101010 == 0