Wednesday, June 7, 2017

326. Power of Three

Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?



Solution:

Method 1: loop

The idea is if n % 3 is 0, we keep divide it by 3 until it is equal or smaller than 1.

At the end we check if n becomes 1.



Code:


public class Solution {
    public boolean isPowerOfThree(int n) {
        if (n > 1) {
            while (n % 3 == 0) {
                n /= 3;
            }
        }
        return n == 1;
    }
}



Method 2: find max power of 3

The idea is to find the largest number in Integer that is the power of 3.

We use this one to mod n.

If the result is 0, n is a power of 3.



Code:


public class Solution {
    public boolean isPowerOfThree(int n) {
        int maxPow3 = (int)Math.pow(3, (int)(Math.log(Integer.MAX_VALUE) / Math.log(3)));
        return n > 0 && maxPow3 % n == 0; 
    }
}