问题描述
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的幂。
又是一道傻逼数学题,正常循环不能用,那我们就用换底公式计算 log3(n) ,看余数是否为0即可。使用了浮点数模除fmod(x, y)方法。
代码
class Solution {
public:
bool isPowerOfThree(int n) {
return fmod(log10(n)/log10(3),1) == 0;
}
};
时间复杂度:
O(1)
空间复杂度:
O(1)
反思
正常的使用循环的做法,TLE了。
class Solution {
public:
bool isPowerOfThree(int n) {
while (n != 1){
if (n % 3 != 0)
return false;
n = n / 3;
}
return true;
}
};
评论区还有用3的20次方模除n的逆天算法(3的21次方超出int范围了),也是傻逼的。