目录结构
1.题目
给定一个整数,写一个函数来判断它是否是 3 的幂次方。
示例:
输入: 27
输出: true
输入: 0
输出: false
输入: 9
输出: true
输入: 45
输出: false
进阶:
你能不使用循环或者递归来完成本题吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/power-of-three
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
2.1模拟
public class Solution326 {
public boolean isPowerOfThree(int n) {
if (n < 1) {
return false;
}
while (n % 3 == 0) {
n /= 3;
}
return n == 1;
}
}
- 时间复杂度:
- 空间复杂度:
2.2进制转换
将整数转换为三进制,若该整数是3的幂,则对应三进制只有一个1。
public class Solution326 {
public boolean isPowerOfThree(int n) {
return Integer.toString(n,3).matches("10*$");
}
}
- 时间复杂度:
- 空间复杂度:
2.3取对数
若整数n是3的幂,即n=3^i,则i=log3(n)为整数。
public class Solution326 {
public boolean isPowerOfThree(int n) {
double i = Math.log10(n) / Math.log10(3);
return i - ((int) i) == 0;
}
}
- 时间复杂度:
- 空间复杂度:
2.4条件限制
根据题设,给定的整数为int型,即32位。
- 故可以获得32位下最大的3的幂MaxPower,若整数n为3的幂,则MaxPower能够被n整除。
public class Solution326 {
public boolean isPowerOfThree(int n) {
int k = (int) (Math.log10(Integer.MAX_VALUE) / Math.log10(3));
int MaxPower = (int) Math.pow(3, k);
return MaxPower % n == 0;
}
}
- 时间复杂度:
- 空间复杂度:
改进。
实际上可以直接计算出MaxPower的值,省去对数运算的开销。
public class Solution326 {
public boolean isPowerOfThree(int n) {
int MaxPower = 1162261467;
return n > 0 && MaxPower % n == 0;
}
}
- 时间复杂度:
- 空间复杂度: