Given an integer n, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three if there exists an integer x such that n == 3^x.
n be negative?
n?
n can range from -2^31 to 2^31 - 1.n is zero?
False.n.n is less than or equal to 0, return False (since powers of three are positive).n by 3 as long as it’s divisible by 3.n equals 1, then it is a power of three; otherwise, it is not.3^19 which is 1162261467.
n must be a divisor of 1162261467 if it lies within the 32-bit integer range.Let’s start with the iterative approach and then also provide the mathematical approach.
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n <= 0:
return False
while n % 3 == 0:
n //= 3
return n == 1
def isPowerOfThreeMathematical(self, n: int) -> bool:
# 3^19 is 1162261467, which is the largest power of three in signed 32-bit integer range.
return n > 0 and 1162261467 % n == 0
n by 3 until n becomes 1.Both approaches effectively determine if a number is a power of three, but the mathematical approach is more efficient due to its constant time complexity.
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?