剑指Offer—33—丑数
来源:互联网 发布:简历管理系统知乎 编辑:程序博客网 时间:2024/06/08 14:26
丑数 : 把只包含因子2、3 和 5 的数称作丑数(Ugly Number)。例如 6、8 都是丑数,但 14 不是,因为它包含因子 7 。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第 N 个丑数。
package A33丑叔;public class Solution { //把只包含因子2、3和5的数称作丑数(Ugly Number)。 //例如6、8都是丑数,但14不是,因为它包含因子7。 // 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。 // 蛮力法 public int GetUglyNumber_Solution(int index) { int count = 0; int num = 0; while (count < index){ ++ num; if (isTrue(num)){ count++; } } return num; } public boolean isTrue(int number) { while (number % 2 == 0) { number = number / 2; } while (number % 3 == 0) { number = number / 3; } while (number % 5 == 0) { number = number / 5; } return number == 1; } public static void main(String[] args) { Solution solution = new Solution(); System.out.println("qwe"); System.out.println(solution.isTrue(2)); }}
package A33丑叔;public class Solution1 { public int GetUglyNumber_Solution(int index) { if (index <= 0) return 0; int[] result = new int[index]; int count = 0; int i2 = 0; int i3 = 0; int i5 = 0; result[0] = 1; int tmp = 0; while (count < index - 1) { tmp = min(result[i2] * 2, min(result[i3] * 3, result[i5] * 5)); if (tmp == result[i2] * 2) i2++;//三条if防止值是一样的,不要改成else的 if (tmp == result[i3] * 3) i3++; if (tmp == result[i5] * 5) i5++; result[++count] = tmp; } return result[index - 1]; } private int min(int a, int b) { return (a > b) ? b : a; } public static void main(String[] args) { Solution1 solution = new Solution1(); solution.GetUglyNumber_Solution(10); }}
阅读全文
0 0
- 剑指Offer—33—丑数
- 剑指offer—丑数
- 剑指offer—丑数
- 剑指offer ——寻找丑数
- 《剑指offer》——丑数
- 剑指offer——丑数
- 剑指Offer——丑数
- 剑指offer——丑数
- 剑指Offer——丑数
- 剑指offer——丑数
- 剑指offer——丑数
- 剑指offer——33.丑数
- 剑指Offer——(33)丑数
- 剑指offer 33 丑数
- 【剑指offer】丑数
- 剑指offer-丑数
- 《剑指offer》丑数
- 【剑指Offer】丑数
- linux磁盘管理
- 使用Java VisualVM监控JVM
- php 通过ssh2协议用sftp实现文件上传、下载
- 算法序列——最长公共子序列
- Step 8:Processing分形之三——Diffusion-Limited Aggregation
- 剑指Offer—33—丑数
- C++ 字节对齐(class 与struct)
- 好用的 CURL 类
- commonjs和ES6及requirejs模块循环引用
- 为啥出现个段错误 求解决方法 在线等哦
- this--浅析
- 金山C++开发笔试
- HTML入门的淘宝注册网页制作
- 二十种实战调优MySQL性能优化的经验