题目:
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(num)必定是正数
这样就可以不用循环就得到结果
class Solution {
public:
bool isPowerOfThree(int n) {
if(n <= 0)
return false;
return n == pow(3, round(log(n) / log(3)));
}
};