题目:
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?
解法1:
在网上看到的解决办法:
<span style="font-size:18px;">class Solution {
public:
bool isPowerOfThree(int n) {
//3^19 = 1162261467, 3^20 is larger than integer
return (n>0 && 1162261467%n == 0);
}
};
</span>
这个方法比较简单而且效率非常高,就是要对3的多少次方大于integer 的最大值要有了解。
常规解法:
<span style="font-size:18px;">class Solution {
public:
bool isPowerOfThree(int n) {
if(n==0)
return false;
if(n==1)
return true;
else
return isPowerOfThree(n/3);
}
};</span>