<LeetCode OJ> 326. Power of Three
2016-01-08 22:44
681 查看
326. Power of Three
My SubmissionsQuestion
Total Accepted: 1159 Total
Submissions: 3275 Difficulty: Easy
判断给定整数是否是3的某次方。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?完成此题,您敢不敢不用迭代或者循环?(那就是递归了呗)
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Tags
Math
Hide Similar Problems
(E) Power of Two
最简单的方法,反复迭代,O(lg(N))的速度
//思路首先:3^x,不管x正负,这个值一定大于0 //如果一个数是3的x次方那么,那么递增i,n一定会在i为某个值等待pow(3,i)完全相等 class Solution { public: bool isPowerOfThree(int n) { if(n==1 || n==3) return true; if( n<3 ) return false; int i=1; while(true) { if(pow(3,i)==n) return true; if(pow(3,i)>n) return false; if(pow(3,i)<n) i++; } } };
和上面的思想一样:递归形式的解法
//思路首先:3^x,不管x正负,这个值一定大于0 //如果一个数是3的x次方那么,那么递增i,n一定会在i为某个值等待pow(3,i)完全相等 //递归形式的解法 class Solution { public: bool isPow3(int n,int step) { if(pow(3,step)==n) return true; if(pow(3,step)>n) return false; if(pow(3,step)<n) return isPow3(n,++step); } bool isPowerOfThree(int n) { int step=0; return isPow3(n,step); } };
相关文章推荐
- 微信支付、公众号支付、微信APP支付教程
- 【数组】Minimum Path Sum
- java:IO流学习小结
- 正则表达式速查
- 算法导论8:数据结构——栈 2016.1.8
- Linux软件安装之源码安装
- 【ITOO 2】.NET 动态建库建表:使用SQL字符串拼接方式
- iOS数据存储的三种方式
- iOS socket编程
- 从二分逼近领略计算科学的魅力
- 【ITOO 3】.NET 动态建库建表:实用EF框架提供的codeFirst实现动态建库
- 【ITOO 2】.NET 动态建库建表:使用SQL字符串拼接方式
- 【ITOO 3】.NET 动态建库建表:实用EF框架提供的codeFirst实现动态建库
- 消息推送,第三方插件集成心得
- 1.8作业
- kinetis design studio配置及程序运行
- 误删除系统libselinux.SO.1,导致系统命令基本上都不能使用--附解决问题的整个过程
- Linux系统启动流程
- CABasicAnimation的基本使用方法(移动·旋转·放大·缩小)
- IBatis配置一对一、一对多两种实现方式