C语言实验——各位数字之和排序
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
给定n个正整数,根据各位数字之和从小到大进行排序。
Input
输入数据有多组,每组数据占一行,每行的第一个数正整数n,表示整数个数,后面接n个正整数。当n为0时,不作任何处理,输入结束。n<=10
Output
输出每组排序的结果。
Sample Input
2 1 2
3 121 10 111
0
Sample Output
1 2
10 111 121
Hint
Source
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n = scanner.nextInt();
if (n == 0) {
break;
}
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = scanner.nextInt();
int r = a[i], k = a[i], sum = 0;
while (k > 0) {
r = r % 10;
k = k / 10;
sum += r;
r = k;
}
b[i] = sum;
}
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (b[j] > b[j + 1]) {
int e = b[j];
b[j] = b[j + 1];
b[j + 1] = e;
e = a[j];
a[j] = a[j + 1];
a[j + 1] = e;
}
}
}
for (int i = 0; i < a.length; i++) {
if (i == a.length - 1) {
System.out.println(a[i]);
} else {
System.out.print(a[i] + " ");
}
}
}
}
}
还有一种(某位Java大佬)比较成熟的做法如下,它不只限于本题的 n <= 10,不提供源码了!