My one line Java solution

  • 5
    public boolean isPowerOfThree(int n) {
        return (Math.log10(n) / Math.log10(3)) % 1 == 0;

    This solution uses math knowledge. If log(n) / log(3) returns an int, then n is a power of 3.

  • 0

    What's the difference from this? They both use math.log and math.log has loop.

    class Solution(object):
        def isPowerOfThree(self, n):
            if n <= 0:
                return False
            r = math.log(n, 3)
            return abs(r - int(math.ceil(r))) < 1e-10

  • 0

    I think your solution uses the same idea as mine. But I didn't find a java log method which provides an option to specify the base, so i used log10() which set 10 as the base.

  • 0

    To be precise, (Math.log10(n) / Math.log10(3)) is a double, not an int. The reason why log10 works but not log (natural log) is only a coincidence in my opinion. You can check out my post here.

  • 0

    I don't think it's a coincidence. (Math.log10(n) / Math.log10(3)) is indeed a double. But when n is a power of 3, (Math.log10(n) / Math.log10(3)) % 1 will be equal to 0. Although it's still a double , but it's a int in double format. That's why this solution works. I actually first tried log(n) and I noticed that log(243) gave me 4.99999... That's why I used log10() instead. But I think that's Java's problem, not this method's problem. Because ideally log(243) should give me 5.0

Log in to reply

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