Power of Four
Topic : Recursion
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 == 4x
.
bool isPowerOfFour(int n) {
if(n<=0) return false;
if(n==1 || n==4) return true;
if(n%4 !=0) return false;
return isPowerOfFour(n/4);
}
public boolean isPowerOfFour(int n) {
return n > 1 && n %4 == 0 ? isPowerOfFour(n/4) : n == 1;
}
class Solution:
def isPowerOfFour(self, n: int) -> bool:
if n == 1:
return True
elif n == 0:
return False
else:
return n%4 == 0 and self.isPowerOfFour(n//4)
Wondering :
class Solution:
def isPowerOfFour(self, n: int) -> bool:
return n > 0 and log2(n) % 2 == 0
Comments
Post a Comment