Algorithm/Java
[백준/자바] 11720번 해설 - Java
isshosng
2022. 2. 16. 22:59
https://www.acmicpc.net/problem/11720
11720번: 숫자의 합
첫째 줄에 숫자의 개수 N (1 ≤ N ≤ 100)이 주어진다. 둘째 줄에 숫자 N개가 공백없이 주어진다.
www.acmicpc.net
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
// N개의 숫자가 공백 없이 쓰여있다. 이 숫자를 모두 합해서 출력하는 프로그램을 작성하시오.
// 첫째 줄에 숫자의 개수 N (1 ≤ N ≤ 100)이 주어진다. 둘째 줄에 숫자 N개가 공백없이 주어진다.
// 입력으로 주어진 숫자 N개의 합을 출력한다.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
// BufferedReader는 객체 생성시 생성자의 입력값으로 InputStreamReader의 객체가 필요함
// InputStream - byte / InputStreamReader - character / BufferedReader - String
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine(); // N은 쓸모가 없으므로 입력만 받음
// readLine() method 이용하려면 예외처리를 해야 함
int sum = 0;
for(byte value : br.readLine().getBytes()) { // getBytes() = 문자열을 byte 배열로 반환
sum += (value - '0'); // UTF-16 인코딩에 맞게 0 또는 48을 빼주어야함
}
System.out.print(sum);
}
}
|
cs |
반응형