Power of Three
来源:互联网 发布:西游之路仙童进阶数据 编辑:程序博客网 时间:2024/04/29 15:05
Power of Three
作者:money
标签:leetcode,C++
问题:
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?
问题分析:
判断一个数是否为3的n次方,选择通过不断除三求余判断。代码效率是有史以来最差的一次。。。
实现代码:
#include <iostream>#include <string>#include <vector>// submit these code to leetcode// beginusing namespace std;class Solution {public: bool isPowerOfThree(int n) { int mods=0; bool istrue=true; if(n<=0) istrue=false; else { while(n>0&&n!=1) { mods=n%3; if(mods==0) {n=n/3;} else { istrue=false; break;} cout<<"mods="<<mods<<endl; cout<<"istrue="<<istrue<<endl; cout<<"n="<<n<<endl; } } return istrue; } };// end// submit these code to leetcodeint main(){ Solution s; int test; bool a; cin>>test; a=s.isPowerOfThree(test); //test case if(a) std::cout<<"true"<<endl; else cout<<"false"<<endl; return 0;}
其他解法
1、递归求余及除3:
public boolean isPowerOfThree(int n) { return n>0 && (n==1 || (n%3==0 && isPowerOfThree(n/3)));}
2、简洁写法:
public boolean isPowerOfThree(int n) { if(n>1) while(n%3==0) n /= 3; return n==1;}
3、int中最大的3的n次方数为1162261467
任何
public boolean isPowerOfThree(int n) { return n > 0 && (1162261467 % n == 0);}
4、通过求
需要注意的是可能存在float类型溢出的情况,貌似使用自然对数ln会出现上述情况。然后判断k是否能被1整除。
public boolean isPowerOfThree(int n) { return (Math.log10(n) / Math.log10(3)) % 1 == 0;}
0 0
- leetcode Power of Three
- Leetcode: Power of Three
- LeetCode Power of Three
- 326. Power of Three
- Leetcode230: Power of Three
- Power of Three
- [leetcode]Power of Three
- LeetCode-Power of Three
- leetcode power of three
- 64. Power of Three
- LeetCode----Power of Three
- 326. Power of Three
- Power of Three
- LEETCODE--Power of Three
- 326. Power of Three
- 【leetcode】Power of Three
- 326. Power of Three
- 326. Power of Three
- Linux for 循环总结
- 软银收购A
- 应用Druid监控SQL语句的执行情况
- 一个lua 与c交互的小demo
- 不需要权限的获取蓝牙mac地址方法
- Power of Three
- Label字体大小自适应label
- SMO算法是干什么的?有什么作用?
- 对抽象,继承,多态的理解
- Servlet学习(五)Cookie
- 树的递归建立与遍历
- Qt 并行框架参考资料和视频
- a++和++a的区别
- IOS存储数据的四种方式