326. Power of Three
2016-02-01 09:32
267 查看
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?
Recursive
Enumerate
Set is slower
<pre name="code" class="java">HashSet<Integer> set = new HashSet<>(Arrays.asList(1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467));
return set.contains(n);
Follow up:
Could you do it without using any loop / recursion?
Recursive
public class Solution { public boolean isPowerOfThree(int n) { return isPower3(n, 0); } public boolean isPower3 (int n, int step){ if(Math.pow(3, step) == n){ return true; }else if(Math.pow(3, step) < n){ return isPower3(n, step+1); }else{ return false; } } }
Enumerate
Set is slower
<pre name="code" class="java">HashSet<Integer> set = new HashSet<>(Arrays.asList(1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467));
return set.contains(n);
return (n == 1 || n == 3 || n == 9 || n == 27 || n == 81 || n == 243 || n == 729 || n == 2187 || n == 6561 || n == 19683 || n == 59049 || n == 177147 || n == 531441 || n == 1594323 || n == 4782969 || n == 14348907 || n == 43046721 || n == 129140163 || n == 387420489 || n == 1162261467);
相关文章推荐
- oracle数据库字符集AL32UTF8修改为ZHS16GBK即从超集到子集
- Android Design Support Library控件使用总结(一)
- swift-函数-1
- Linux上pip安装cx_Oracle
- React 入门实例教程
- CSS 参考文档
- oracle11g RAC添加节点
- 等高分栏布局小结
- 浅谈Linux内存管理机制
- Angular.js(出库编辑)
- MySQL内核整理(一)
- linux和windows下自动备份作业与自动作业删除
- 使用 xib 创建 tableViewCell
- oracle-12c-rac 报:ORA-01078
- 11G RAC 简单命令
- hexo换了电脑处理方法
- jQuery与Ajax以及序列化
- 堆栈溢出问题 调试到位置(test dword ptr [eax],eax ; probe page.)
- ORA-14404
- jsp实现的教育类网站前台页面