leetcode : 326. Power of Three

Posted on

A small and simple recursive solution to the power of 3 problem.

What the problem is asking for is if the value given is a power of 3. So 9 or 27 would be true because 3*3=9, and 3*3*3=27.

A number who has 3 has one of it’s factors would be false. Example 18, which is 3*3*2 is not a power of three

var isPowerOfThree = function(n) {
    //base case : 3 to the power of 0 is 1
    if(n === 1){return true}
    //Since JS uses floating numbers, eventually when you keep dividing by 3
    //the value of n will either be 3,1, or some floating number less than 3 
    if(n < 3){return false}
    //either we end up with n as 3, or we call our function again 
    return ( n / 3 === 1 || isPowerOfThree(n/3))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s