Saturday, October 15, 2016

Power of Three

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

If the number mod 3 is not 9, return false. Otherwise recursively check if it can be mod by 3, until it reaches 1.


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


No comments:

Post a Comment