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?
解:
方法一:
public class Solution {
public boolean isPowerOfThree(int n) {
if(n ==0){
return false;
}
return (n == Math.pow(3,Math.round((Math.log(n)/Math.log(3)))));
}
}
方法二:
public class Solution {
public boolean isPowerOfThree(int n) {
if(n ==0){
return false;
}
int t = pow(3,(int)log(INT_MAX)/log(3));
return (t%n == 0);
}
}
tips:
INT_MAX 定义的最大的整数,也就是说衡量无穷大的整数
Math.round(double); 四舍五入
(int)double 强制转换 只保留整数部分
Math.floor()四舍五入