Header Ad

Leetcode Power of Three problem solution

In this Leetcode Power of Three problem solution, You are 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.

Leetcode Power of Three problem solution


Problem solution in Python.

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n == 1:
            return True
        elif n < 3:
            return False
        
        if not n%3:
            return self.isPowerOfThree(n/3)
        return False



Problem solution in Java.

public boolean isPowerOfThree(int n) {
    int c=0;
    boolean x=false;
    if(n!=0){
    while(c==0){
        if(n==1){
            x=true;
            break;
        }
        c=n%3;
        n=n/3;
    }
    }
    return x;
}


Problem solution in C++.

class Solution {
public:
bool isPowerOfThree(int n) {

    if(n==0){
        return false;
    }
    
    while(n!=1){
        
        if(n%3!=0){
            return false;
        }
        
        n=n/3;
        
    }
    
    return true;  
}
};


Problem solution in C.

bool isPowerOfThree(int n) {
    if(n==0)
    {return false;}
    else if(n==1||n==3||n==9)
    {return true;}
    else if(n%9!=0)
    {return false;}
    return isPowerOfThree(n/9);
}


Post a Comment

0 Comments