題目:按從小到大的順序輸出前n個醜數,習慣上把1當做第一個醜數;
代碼如下:
public class UglyNum {
public static void main(String[] args) {
// 要輸出的醜數個數
int des = 1500;
// 結果數組
int[] result = new int[des];
result = GetUglyNumber_Solution(des);
int count = 0;
for (int i = 0; i < result.length; i++) {
System.out.print(result[i] + " ");
count++;
if (count % 10 == 0) {
System.out.println();
}
}
}
public static int[] GetUglyNumber_Solution(int index) {
if (index <= 0) {
return null;
}
int[] uglyNum = new int[index];
uglyNum[0] = 1;
int nextUglyIdex = 1;
int multiply2 = 0;
int multiply3 = 0;
int multiply5 = 0;
while (nextUglyIdex < index) {
int minUgly = Math.min(uglyNum[multiply2] * 2,
Math.min(uglyNum[multiply3] * 3, uglyNum[multiply5] * 5));
uglyNum[nextUglyIdex] = minUgly;
while (uglyNum[multiply2] * 2 <= uglyNum[nextUglyIdex]) {
multiply2++;
}
while (uglyNum[multiply3] * 3 <= uglyNum[nextUglyIdex]) {
multiply3++;
}
while (uglyNum[multiply5] * 5 <= uglyNum[nextUglyIdex]) {
multiply5++;
}
nextUglyIdex++;
}
return uglyNum;
}
}
輸出結果: