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?
提高:
你能不用循环或递归实现吗?
这道题应该不用解释了吧。。。
class Solution {
public:
bool isPowerOfThree(int n) {
while(n>1){
if(n%3!=0) return false;
n/=3;
}
if(n==1) return true;
return false;
}
};
倒是提高的我花了几分钟没有想出来就没想了,看讨论里有人给出了一个答案:
bool isPowerOfThree(int n)
{
double logRes = log10(n)/log10(3);
return (logRes - int(logRes) == 0) ? true : false;
}
就是判断log3(n)是否为整数。。。看完之后感觉自己好蠢啊。。。这么简单都没想出来
不过没想到C++里居然还有log和log10这么"浅显"的函数。。。长见识了