Wednesday, January 27, 2016

326. Power of Three

Q:
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?
A:
递归:

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

************ 代数 计算 ******  取Log

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


No comments:

Post a Comment