Given an integer n
, return true
if it is a power of four. Otherwise, return false
.
An integer n
is a power of four, if there exists an integer x
such that n == 4ˣ
.
class Solution(object):
def isPowerOfFour(self, n, count = 1):
"""
:type n: int
:rtype: bool
"""
if n == 4:
return True
if n > 4:
return self.isPowerOfFour(pow(n,1/count),count + 1)
I keep getting False as an output
If I pass an input that's less than 4
, e.g. 2
, your function will return None
. I'm not sure why you say that the function returns False
, but I think that might just be some quirk in LeetCode's testing infrastructure.
Anyway, to solve this problem using recursion, we make three observations:
1
is a power of 4.n > 1
, if n
can be expressed as 4^x
for some integer x
, then so can n // 4
(as it would be equivalent to 4^(x - 1)
).This gives us the following recursive solution:
class Solution(object):
def isPowerOfFour(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 1:
return True
elif n % 4 != 0:
return False
return self.isPowerOfFour(n // 4)