题目:
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>
本文提供了一种高效的算法来判断给定的整数是否为3的幂,通过使用特定的数值比较避免了循环和递归。
614

被折叠的 条评论
为什么被折叠?



