Follow up: Could you do it without using any loop / recursion?
递归:
public class Solution { public static boolean isPowerOfThree(int n) { int c=0; if(n<=0) return false; if(n==1) return true; else if(n%3==0) { return isPowerOfThree(n/3); } else return false; } }迭代:
public class Solution { public boolean isPowerOfThree(int n) { if (n <= 0) return false; while (n != 1) { if (n%3 != 0) break; n /= 3; } return n==1; } }数学方法:
public static boolean isPowerOfThree1(int n) { double res=Math.log(n)/Math.log(3); return Math.abs(res - Math.rint(res))< 0.0000000001; }