Power of Three
2016-07-19 12:17
281 查看
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 // begin using 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 leetcode int 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
任何3n 均为该数的因子:
public boolean isPowerOfThree(int n) { return n > 0 && (1162261467 % n == 0); }
4、通过求
n=3k
k=log3n=log10nlog103
需要注意的是可能存在float类型溢出的情况,貌似使用自然对数ln会出现上述情况。然后判断k是否能被1整除。
public boolean isPowerOfThree(int n) { return (Math.log10(n) / Math.log10(3)) % 1 == 0; }
相关文章推荐
- 不需要权限的获取蓝牙mac地址方法
- 一个lua 与c交互的小demo
- D. Puzzles(Codeforces Round #362 (Div. 2))
- 利用python脚本实现域名解析和归属地信息查询
- hdoj 1280 前m大的数 【sort】
- 一句reload,解决了千古难题
- Linux for 循环总结
- CAKeyframeAnimation关键帧动画的相关属性和方法
- 2-Application Layer
- hdu 4277 USACO ORZ
- 我的助理辞职了
- 了解Java基础
- Tablayout 的使用
- 直方图相似度算法
- android压缩图片 遇到的问题
- 好的开源工程
- hdoj 2187 老人是真饿了 【结构体+贪心】
- STL概述
- C++中临时对象的学习笔记
- 输出格式 c && c++