-
Notifications
You must be signed in to change notification settings - Fork 2
/
UglyNumber.java
85 lines (75 loc) · 1.79 KB
/
UglyNumber.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package org.offer.case34;
/**
* 面试题 34:丑数
* Created by tanc on 17-6-9.
*/
public class UglyNumber {
/**
* 方法一:遍历
*/
public static long printUglyNumber(int n) {
int count = 0;
int i = 1;
while (true) {
if (isUgly(i)) {
count++;
if (count == n) {
return i;
}
}
i++;
}
}
public static long methodTwo(int n) {
// 存放丑数序列
long[] uglyNumbers = new long[n];
// 第一个丑数为 1
uglyNumbers[0] = 1;
int ugly2p = 0;
int ugly3p = 0;
int ugly5p = 0;
int p = 1;
while (p < n) {
long num2p = uglyNumbers[ugly2p] * 2;
long num3p = uglyNumbers[ugly3p] * 3;
long num5p = uglyNumbers[ugly5p] * 5;
long min = min(num2p, num3p, num5p);
uglyNumbers[p++] = min;
if (num2p == min) {
ugly2p++;
}
if (num3p == min) {
ugly3p++;
}
if (num5p == min) {
ugly5p++;
}
}
return uglyNumbers[n - 1];
}
private static long min(long a, long b, long c) {
long result = a;
if (b < result) {
result = b;
}
if (c < result) {
result = c;
}
return result;
}
/**
* 判断一个数是否为丑数
*/
private static boolean isUgly(long number) {
while (number % 2 == 0) {
number /= 2;
}
while (number % 3 == 0) {
number /= 3;
}
while (number % 5 == 0) {
number /= 5;
}
return number == 1;
}
}