Python without loop or recursive statements.

  • 0
        def isPowerOfThree(self, n):
            :type n: int
            :rtype: bool
            lb = 2*(len(str(n))-1)  
            if 3**lb==n or 3**(lb+1)==n or 3**(lb+2)==n:
                return True
                return False

    For any integer n, we define m=len(str(n))-1 to construct the bounds:
    10**m <= n <= 10**(m+1).
    Then, we took logarithm base 3 to obtain
    2*m < m*log_3(10) <= log_3(n) <= (m+1)*log_3(10)
    if n is a power of 3, then log_3(n) must be an integer between these two bounds. We observe that:
    log_3(10)(m+1) - log_3(10)(m)= log_3(10) ~ 2.096 < 3
    so we only need to try 3**m,3**(m+1) and 3**(m+2)

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.