본문 바로가기
알고리즘 문제연습/기초 알고리즘

[015] 입력된 숫자의 개수 출력하기

by 은z 2021. 5. 27.

문제

- 입력된 숫자의 개수를 출력하시오

입력 : 4214215218

결과

0: 0

1: 2

2: 3

3: 0

4: 2

5: 1

6: 0

7: 0

8: 1

9: 0

 

- 중첩반복문 이용, 배열

 

보완할 점

 

소스코드

package Algorithm;

import java.util.Scanner;

public class Algorithm13 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		String num = sc.next(); //글자수 세기 위해서 String으로 선언
		
		int[] arr = new int[10];
		
		for(int i = 0; i < num.length(); i++) { //입력한 숫자
			for(int j = 0; j < arr.length; j++) { // 배열
				if((num.charAt(i) - '0') == j) { 
					arr[j] += 1; //+1씩 해당배열에 저장
				}
			}
		}
		//출력
		for(int i = 0; i < arr.length; i++) {
			System.out.println(i + ": " + arr[i]);
		}
	}
}

댓글