Leetcode: Power of three
Given a number n, check if this number is a power of three, that is that it can be represented by 3^x.
A straightforward solution looks as follows. Multiply by 3 until we reach n. If we’re greater than n, return False, and True otherwise.
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n <= 0:
return False
x = 1
while x < n:
x *= 3
return x == n2^31: 3^19. Then use the modulo operator to test if the number is divisible without a rest. If this is the case, x*n == 3^19, therefore n is a valid number.
class Solution:
def isPowerOfThree(self, n: int) -> bool:
return n > 0 and pow(3,19) % n == 0
Runtime: 80 ms, faster than 95.46% of Python3 online submissions for Power of Three. Memory Usage: 13.9 MB, less than 16.48% of Python3 online submissions for Power of Three.