题目:
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?
题目的关键在于不使用循环和递归,想了很久也没有想到合适的,看了discuss之后才知道是一个数学问题,好吧,我承认自己忘记对数了。。。
代码如下:
public class Solution {
public boolean isPowerOfThree(int n) {
if(n < 1){return false;}
// Math.log(n) / Math.log(3)会出错,Math.log是以e为底的
double res = Math.log10(n) / Math.log10(3);
if(res%1 == 0){
return true;
}else{
return false;
}
}
}
【注】
不明白为什么使用Math.log会出错。。。求解答。。。