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>
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>
相关文章推荐
- java版精简搜狗皮肤
- shell下的进程
- LeetCode *** 16. 3Sum Closest
- 最长公共子串 | 阿里2015笔试附加题2
- UNP(一):网络编程角度下的TCP、UDP协议
- 在 Visual C# 中,如何为 TextBox 控件添加水印文字
- GOF设计模式快速学习
- easyUI设置下拉列表默认值
- OpenGL纹理使用
- centos 安装MySQL
- 想要用例管理更便捷?这些工具来帮忙!
- 训练MNIST数据集模型
- 9i中的数据保护模式
- 第八周计算任务
- 鸭子类型(wiki)
- s标签遍历中的遍历
- 文件服务器解决方案(项目源码)
- Apache与Tomcat联系及区别
- R语言︱排序问题
- mysql数据库在Navicat Premium连接的时候出现1862错误