您的位置:首页 > 其它

LeetCode 刷题 -- power of three

2016-04-18 16:27 411 查看
题目:

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: