1064. Number of friends (20) (full score in Java)

If the sum of the digits of two integers is the same, it is called "friend number", and that common sum is their "friend card number". For example, 123 and 51 are friend numbers, because 1+2+3 = 5+1 = 6, and 6 is their friend ID number. Given some integers, you are asked to count how many different friend IDs there are. Note: We default an integer to be its own friend.

Input format:

The first line of input gives a positive integer N. The next line gives N positive integers separated by spaces. The question guarantees that all numbers are less than 10 4 .

Output format:

First, the first line outputs the number of different friend IDs in the given number; the next line outputs these friend IDs in increasing order, the numbers are separated by a space, and there must be no extra spaces at the end of the line.

Input sample:
8
123 899 51 998 27 33 36 12
Sample output:
4
3 6 9 26
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int n = input.nextInt();

		Set<Integer> friend = new TreeSet<Integer>();
		for (int i = 0; i < n; i++) {
			int sum = 0;
			int f = input.nextInt();
			
			while (f != 0) {
				sum += f % 10;
				f /= 10;
			}
			friend.add(sum);
		}
		input.close();

		System.out.println(friend.size());
		boolean isFirst = true;
		for (int id : friend) {
			if (!isFirst) {
				System.out.print(" ");
			}
			System.out.print(id);
			isFirst = false;
		}
	}

}
This question is not difficult if you know the set set, the main thing is to pay attention to the difference between the hashset and the treeset:

1. TreeSet is implemented by binary tree. The data in Treeset is automatically sorted, and null values ​​are not allowed. 

2. HashSet is implemented by a hash table. The data in HashSet is disordered and can be put in null, but only one null can be put in, and the values ​​in both cannot be repeated, just like the unique constraint in the database. 

3. HashSet requires that the placed objects must implement the HashCode() method. The placed objects are identified by the hashcode code, and the String objects with the same content have the same hashcode, so the placed content cannot be repeated. But objects of the same class can be put into different instances.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325345086&siteId=291194637