Count Occurrences
Completed
Read n integers between 0 and 9. Print how many times each digit 0–9 appears, as digit: count, skipping digits that never appear.
Input
Line 1: n. Line 2: n integers.
Output
One line per digit that appears.
Example
Input
8 3 1 3 9 0 3 1 9
Output
0: 1 1: 2 3: 3 9: 2
Editor
Java
Hints
Use the value itself as an index into a counts array.
Solution explanation
A counting array turns "how many of each" into one pass over the data.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] counts = new int[10];
for (int i = 0; i < n; i++) {
counts[sc.nextInt()]++;
}
for (int d = 0; d < 10; d++) {
if (counts[d] > 0) {
System.out.println(d + ": " + counts[d]);
}
}
}
}