Java练习 SDUT-1188_各位数字之和排序

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

可以开两个数组,一个存储原数字,一个存储各位数字之和,然后排序是一起变动就可以,不过想到了C里的结构体,Java的类也是类似的功能。

import java.util.*;

public class Main {

	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		num[] a = new num[15];
		num t = new num();
		int n,i,j;
		for(i=0;i<15;i++)
			a[i] = new num();
		while(cin.hasNextInt())
		{
			n = cin.nextInt();
			if(n==0)
				break;
			for(i=0;i<n;i++)
			{
				a[i].x = cin.nextInt();
				a[i].b = a[i].f();
			}
			for(i=0;i<n;i++)
				for(j=0;j<n-i-1;j++)
					if(a[j].b>a[j+1].b)
					{
						t = a[j];
						a[j] = a[j+1];
						a[j+1] = t;
					}
			for(i=0;i<n;i++)
				if(i==n-1)
					System.out.println(a[i].x);
				else
					System.out.print(a[i].x+" ");
		}
		cin.close();
	}
}

class num
{
	int x,b;
	int f()
	{
		int a = x,sum = 0;
		while(a!=0)
		{
			sum += a%10;
			a /= 10;
		}
		return sum;
	}
}
posted @ 2018-09-26 23:49  洛沐辰  阅读(463)  评论(0编辑  收藏  举报