描述
给定一组n个正整数,根据各位数字之和从小到大进行排序。
输入
输入数据有多组,每组数据占一行,每行的第一个数正整数n,表示整数个数,后面接n个正整数。当n为0时,不作任何处理,输入结束。
输出
输出每组要求下原始数据排序的结果。
样例输入
2 1 2
3 121 10 111
0
样例输出
1 2
10 111 121
思路:提到排序,就可以想到Arrays.sort方法,但这里是根据数的各位之和的大小进行排序,所以需要自定义排序方法(重写compara方法),需要注意的是重写comparable方法需要继承Comparactor接口,而接口只支持非基本类数据,所以排序时要用Integer类数据,Java中有自动装箱和拆箱功能,不需要使用方法进行转换
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
while ((n = sc.nextInt()) != 0 ) {
Integer[] num = new Integer[n];
for (int i = 0; i < n; i++)
num[i] = sc.nextInt();
MyComparactor myComparactor = new MyComparactor();
Arrays.sort(num, myComparactor);
for (int i = 0; i < n; i++) {
if ( i < n-1 ) System.out.print(num[i] + " ");
else System.out.println(num[i]);
}
}
}
}
class MyComparactor implements Comparator<Integer> {
public int compare(Integer o1, Integer o2) {
int a = SumDigit(o1);
int b = SumDigit(o2);
if ( a < b ) return -1;
else if ( a > b ) return 1;
else return 0;
}
//定义方法求数字各位之和
public int SumDigit(Integer a) {
int num = a, sum = 0;
while ( num != 0 ) {
sum += num %10;
num /= 10;
}
return sum;
}
}