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?
判断一个数是否是3的次方?
法1:网友神奇方法
public boolean isPowerOfThree(
int n) {
return ( n>
0 &&
1162261467%n==
0);
}
法2:借助对数函数
public boolean
isPowerOfThree(
int n) {
if(n<=
0)
return false;
double d = log(n,
3);
int t = (
int) Math.floor(d+
0.1);
return n==Math.pow(
3, t);
}
public double log(
double value,
double base) {
return Math.log(
value) / Math.log(
base);
}
转载请注明原文地址: https://ju.6miu.com/read-6073.html