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^x.
n?
n is a 32-bit signed integer.n = 0 or n = 1?
n = 0 should return false, and n = 1 should return true since 4^0 = 1.Initial Check: If n is less than or equal to zero, it cannot be a power of four. Return false.
n is a power of four if log4(n) is an integer. We can use the change of base formula:
log4(n) = log(n) / log(4)n is a power of four.1 followed by an even number of 0s. This property makes the bitwise AND operation useful.n & (n - 1) == 0).3 should be 1 (since 4^x % 3 = 1).Here, we’ll go with the bit manipulation approach as it is more efficient in terms of time complexity.
def isPowerOfFour(n: int) -> bool:
if n <= 0:
return False
return (n & (n - 1)) == 0 and (n % 3 == 1)
n is non-positive (n <= 0), return false.(n & (n - 1)) == 0 checks if n is a power of two.(n % 3 == 1) ensures n is specifically a power of four by checking its modulo 3.The time complexity of this approach is O(1) because all the operations involved (bitwise AND, comparison, and modulo) are constant time operations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?