No-loop, no-recurse solution for Python

  • 2

    This can be done in one line, as you'll see elsewhere, but this solution makes it pretty clear what's going on. I was having trouble for a while because I was using sys.float_info.epsilon for my epsilon value. But in this forum I saw someone using 1e-10, and that does the trick.

    from math import log
    class Solution(object):
        def isPowerOfThree(self, n):
            :type n: int
            :rtype: bool
            if n <= 0:
                return False
                cube_root = log(n)/log(3)
                cube_root_rounded = round(cube_root)
                diff = abs(cube_root - cube_root_rounded)
                return True if diff <= 1e-10 else False

  • 0

    What's the advantage of

    return True if diff <= 1e-10 else False


    return diff <= 1e-10


  • 0

    No advantage.

Log in to reply

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