题目
给定一个整数,写一个函数来判断它是否是 3 的幂次方。
示例 1:
输入: 27
输出: true
示例 2:
输入: 0
输出: false
示例 3:
输入: 9
输出: true
示例 4:
输入: 45
输出: false
代码
1.使用循环
class Solution {
public boolean isPowerOfThree(int n) {
while(n>1 && n%3==0){
n = n/3;
}
return n==1;
}
}
2.不使用循环,使用库函数
import java.lang.*;
class Solution {
public boolean isPowerOfThree(int n) {
double result = Math.log10(n)/Math.log10(3);
return result == (int)result;
}
}