LeetCode #326 Power of Three Solution & Explanation

LeetCode Problem

Given an integer n, return true if it is a power of three. Otherwise, return false.

An integer n is a power of three, if there exists an integer x such that n == 3x.

Follow up: Could you solve it without loops/recursion?


Solution

Same as the solution of power of two, we can just modify 2 to 3

C# Solution

Solution1

public class Solution {
    public bool IsPowerOfThree(int n) {
        if(n<0){
            return false;
        }

        double nn = n*1.0;
        while(nn>=3)
        {
            nn/=3;
        }
        return nn == 1.0;
    }
}

Java Solution

Solution1

class Solution {
    public boolean isPowerOfThree(int n) {
        if(n<0){
            return false;
        }

        double nn = n*1.0;
        while(nn>=3)
        {
            nn/=3;
        }
        return nn == 1.0;
    }
}

Python3 Solution

Solution1

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        if(n<0):
            return False

        while(n>=3):
            n=n/3

        return n == 1

JavaScript Solution

Solution1

/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfThree = function(n) {
    if(n<0){
        return false;
    }

    while(n>=3)
    {
        n/=3;
    }
    return n == 1;
};

Conclusion

We’ve solved this problem using a loop.

However, for the follow-up, there is certainly another solution. I’ll take some time to think about it, and I’ll update the post ASAP!

🧡If my solution helps, that is my honor!

🧡You can support me by sharing my posts or clicking ads, thanks you~~

✅If you got any problem about the explanation or you need other programming language solution, please feel free to let me know !!

The problem link : Power of Three – LeetCode

Some Random Posts

Leave a Reply

Your email address will not be published. Required fields are marked *