7-4求一批整數中出現最多的個位數字(20分)

在這裏插入圖片描述

參考代碼

public class Main {
	public static void main(String[] args) {
		int [] a = new int[10]; // 用於記錄數字出現的次數
		int numMax = 0;
		
		Scanner cin = new Scanner(System.in);
		
		int n = cin.nextInt();
		
		for( int i = 0; i < a.length; i ++ ) { // 清零
			a[i] = 0;
		}
		
		for(int i = 0; i < n; i ++ ) {
			int t = cin.nextInt();
			
			if( t == 0 ) {
				a[t] ++;
			}
			else {
				while( t > 0 ) {
					a[t % 10 ] ++;
					t /= 10;
				}
			}
		}
		
		for(int i = 0; i < a.length; i ++ ) { // 找到數字出現最多的次數
			if( a[i] > numMax ) {
				numMax = a[i];
			}
		}
		
		System.out.print(numMax + ":");
		for( int i = 0; i < a.length; i ++ ) {
			if( a[i] == numMax ) {
				System.out.print(" " + i);
			}
		}
		System.out.println();
		
		cin.close();
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章