LeetCode -- Power of Three
2016-02-13 10:17
393 查看
Question:
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?
Analysis:
给出一个整数,写一个函数判断它是否是3的n次幂。
注意:能否不用循环或递归解决这个问题?
Solution1: Using Loop.
Solution2: Using Recursion.
Solution3: Using Log Function. (logab = logcb / logca)
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?
Analysis:
给出一个整数,写一个函数判断它是否是3的n次幂。
注意:能否不用循环或递归解决这个问题?
Solution1: Using Loop.
//Solution1: Loop public boolean isPowerOfThree(int n) { if(n <= 0) return false; while(n > 1) { if(n % 3 != 0) break; else n /= 3; } return n == 1; }
Solution2: Using Recursion.
//Solution2: Recursion. public static boolean isPowerOfThree(int n) { if(n <= 0) return false; if(n == 1) return true; if(n % 3 == 0) return isPowerOfThree(n/3); else return false; }
Solution3: Using Log Function. (logab = logcb / logca)
public boolean isPowerOfThree(int n) { if(n <= 0) return false; double log = Math.log10(n) / Math.log10(3); if(log - (int)log == 0) return true; else return false; }
相关文章推荐
- [LeetCode]142. Linked List Cycle II
- C++构造函数与析构函数
- 上传文件2.0--drp203
- play-framework的安装与使用
- 数据结构实验之链表七:单链表中重复元素的删除
- iOS-基础动画
- 第十章泛型算法
- Codeforces Round #342 (Div. 2) 625A Guest From the Past(贪心)
- 我也有博客了
- Machine Learning - An Introduction
- 【JAVA】7、运算符
- 树莓派 Raspberry Pi SD卡系统备份与还原
- 查找单链表的中间元素
- 一小球从100米高度自由落下,每次落地后反跳回原高度的一半,再落下。
- Hadoop 排序 SortData
- 数组的一个强大函数splice,[增,删,改]
- BlogApp之spring整合Guava中的AsyEventBus异步事件
- Monty Hall Simulations
- 软件开发技术:DRY
- javascript实现查找数组中最大值方法汇总