LeetCode – Power of Three (Java)

Given an integer, write a function to determine if it is a power of three.

Java Solution 1 - Iteration

public boolean isPowerOfThree(int n) {
    if(n==1) return true;
 
    boolean result = false;
 
    while(n>0){
        int m = n%3;
        if(m==0){
            n=n/3;
            if(n==1)
                return true;
        }else{
            return false;
        }
    }
 
    return result;
}

Java Solution 2 - Recursion

public boolean isPowerOfThree(int n) {
    if(n==0) 
        return false;
 
    if(n==1) 
        return true;
 
    if(n>1) 
        return n%3==0 && isPowerOfThree(n/3);
    else
        return false;
}

Java Solution 3 - Math

public boolean isPowerOfThree(int n) {
    if(n==0) return false;
 
    return n == Math.pow(3, Math.round(Math.log(n)/Math.log(3)));
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • MJ

    Another simple solution –
    // numbers are – 1,3,9,27,81,243,729,2187,6561…..
    // pattern is -divide by 3 power 2(number of digits -1) should be divisble by 3 or 9

    if(n == 1 || n==3 || n==9){
    return true;
    }
    else{
    var a = n / (Math.Pow(3, 2*(n.toString().length() – 1)));
    if (a == 3 || a == 9)
    {
    return true;
    }
    return false;
    }