Leetcode——326. Power of Three
2017-01-21 20:27
471 查看
题目
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?
解答
Method1:循环或者递归public boolean isPowerOfThree(int n) { return n>0 && (n==1 || (n%3==0 && isPowerOfThree(n/3))); }
public boolean isPowerOfThree(int n) { if(n>1) while(n%3==0) n /= 3; return n==1; }
因为3是质数,所以可以用最大的3的幂次和n求模来计算。
最大的的3的幂次:
int MaxPowerOfThree=(int) pow(3,(int)(log10(INT_MAX)/log10(3)));
AC code
class Solution { public: bool isPowerOfThree(int n) { int MaxPowerOfThree=(int) pow(3,(int)(log10(INT_MAX)/log10(3))); return n>0&&MaxPowerOfThree%n==0; } };
Or simply hard code it since we know maxPowerOfThree = 1162261467: public boolean isPowerOfThree(int n) { return n > 0 && (1162261467 % n == 0); }
相关文章推荐
- 局域网访问本机的虚拟机项目(桥接方式最佳 )
- 堆
- InfoSYS-20170114
- 设计模式的原则
- 开发板linux中运行简单hello world应用程序的printf无输出的原因
- 开发板linux中运行简单hello world应用程序的printf无输出的原因
- 开发板linux中运行简单hello world应用程序的printf无输出的原因
- 开发板linux中运行简单hello world应用程序的printf无输出的原因
- 开发板linux中运行简单hello world应用程序的printf无输出的原因
- 开发板linux中运行简单hello world应用程序的printf无输出的原因
- priority_queue优先级重载
- 线段树
- OpenWrt 中安装配置Transmission
- python应用 (1) 解析xml
- iOS动画案例(1) 类似于qq账号信息里的一个动画
- 【设计模式】--代理模式 (Proxy模式)
- 【清明】并查集
- struts基本概念(2)
- More Effective C++学习笔记(4)-效率
- C#与C++在语法上的区别