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的幂。。。宝宝心里苦。。。
这首先就是想递归啊。。。
class Solution {
public:
bool isPowerOfThree(int n) {
if(n <= 0)
return false;
if(n == 1)
return true;
if(n % 3 == 0)
{
if(n == 3)
return true;
return isPowerOfThree(n / 3);
}
return false;
}
};
最开始的两个if简直的神坑。。。宝宝总掉坑。。。
至于follow up。。。
有个这货。。。
pow() 函数用来求 x 的 y 次幂(次方),其原型为:
double pow(double x, double y);
pow()用来计算以x 为底的 y 次方值,然后将结果返回。设返回值为 ret,则 ret = xy。
class Solution {
public:
bool isPowerOfThree(int n) {
return n <= 0 ? false : n == pow(3, round(log(n) / log(3)));
}
};
that’s it
但是时间。。。比递归还慢啊。。。噗。。。