PowerOfThree
Problem
Solution
Note that, if \(n = 3^x\), \(n\) can never be negative. For positive \(n`\), check if \(n\) is divisble by 3. If it is, divide \(n\) by 3 and check again. If it is not, then \(n\) is not a power of 3.
Code
https://github.com/GeorgeRPu/tech-interview-prep/blob/main/solutions/PowerOfThree.py
def isPowerOfThree(n: int) -> bool:
"""Check if ``n`` is a power of 3.
"""
if n <= 0:
return False
elif n == 1:
return True
elif n % 3 == 0:
return isPowerOfThree(n / 3)
else:
return False
Test
>>> from PowerOfThree import isPowerOfThree
>>> isPowerOfThree(27)
True
>>> isPowerOfThree(0)
False
>>> isPowerOfThree(-1)
False
Functions
|
Check if |