Question:
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?
Analysis:
给出一个整数,写一个函数判断它是否是3的n次幂。
注意:能否不用循环或递归解决这个问题?
Solution1: Using Loop.
//Solution1: Looppublic boolean isPowerOfThree(int n) { if(n <= 0) return false; while(n > 1) { if(n % 3 != 0) break; else n /= 3; } return n == 1;}
Solution2: Using Recursion.
//Solution2: Recursion.public static boolean isPowerOfThree(int n) { if(n <= 0) return false; if(n == 1) return true; if(n % 3 == 0) return isPowerOfThree(n/3); else return false;}
Solution3: Using Log Function. (logab = logcb / logca)
public boolean isPowerOfThree(int n) { if(n <= 0) return false; double log = Math.log10(n) / Math.log10(3); if(log - (int)log == 0) return true; else return false; }