math and geometry August 24, 2022

Power of three

Time O(log(n)) Space O(1) Open original problem

We will devide the number by 3 until it's 1. If in any step, we have any reminder, we will return false, otherwise return true.

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        if n == 1:
            return True
        if n < 3:
            return False
        while n > 1:
            if n % 3 == 0:
                n /= 3
            else:
                return False
        return True

Time Complexity: O(log(n))
Space Complexity: O(1)