Java—各位数字之和排序

    科技2024-08-02  62

    Java—各位数字之和排序

    Description 给定n个正整数,根据各位数字之和从小到大进行排序。

    Input 输入数据有多组,每组数据占一行,每行的第一个数正整数n,表示整数个数,后面接n个正整数。当n为0时,不作任何处理,输入结束。n<=10

    Output 输出每组排序的结果。

    Sample Input 3 230 59 110 5 199 220 108 235 120 0 Output 110 230 59 120 220 108 235 199

    import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner reader = new Scanner(System.in); int n, i, j; int temp; while (reader.hasNext()) { int a[] = new int[20]; int b[] = new int[20]; int c[] = new int[20]; n = reader.nextInt(); if (n == 0) break; else { for (i = 0; i < n; i++) { a[i] = reader.nextInt(); b[i] = a[i]; } for (i = 0; i < n; i++) { while (b[i] != 0) { c[i] = c[i] + b[i] % 10; b[i] = b[i] / 10; } } for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if (c[i] > c[j]) { temp = c[i]; c[i] = c[j]; c[j] = temp; temp = a[i]; a[i] = a[j]; a[j] = temp; } } } for (i = 0; i < n - 1; i++) { System.out.print(a[i] + " "); } System.out.println(a[n - 1]); } } } }
    Processed: 0.011, SQL: 9