Tiny Bunny
본문 바로가기
Java/백준

백준 11720번 - 숫자의 합

by 내이름효주 2024. 1. 9.

[내가 짠 코드] - 틀린 버전

import java.util.Scanner;

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

		for (int n = 0; n < a; n++) {
			int x = sc.nextInt();
			String s = Integer.toString(x);
			int[] arr = new int[s.length()];
			int sum = 0;
			
			for (int i = 0; i < arr.length; i++) {
				arr[i] = s.charAt(i) - '0';
				sum += arr[i];
			}
			System.out.print(sum);
		}
		sc.close();
	}
}

- 이렇게 제출하니까 런타임 에러 (InputMismatch)  뜸

- 11 10987654321 이 예시를 적용해보면 저런 에러가 뜸

- 두번째 정수를 받는 곳에서 int로 받는데 int의 범위보다 커서 뜨는 에러였음

 

[내가 짠 코드] - 정답

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		String s = sc.next();
		int sum = 0;

		for (int n = 0; n < a; n++) {
			sum += s.charAt(n) - '0';
		}
		System.out.print(sum);
		sc.close();
	}
}

- 두번째 정수 자체를 문자로 받고 문자 0이랑 빼서 정수로 바꾼애를 sum에 넣음