Power of Three(Easy)

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?

Java代码


public boolean isPowerOfThree(int n) {
     //1162261467=3^19. 3^20 is bigger than int
     return n<1 ? false : 1162261467%n == 0 ? true : false ;
}

OR

public static boolean isPowerOfThree(int n) {
    if (n <= 0)
            return false;

    double r = Math.log10(n) / Math.log10(3);
    if (r % 1 == 0)
        return true;
    else
        return false;
}

References

  1. LeetCode Article: Power of Three

results matching ""

    No results matching ""