https://www.acmicpc.net/problem/11720
문제
N개의 숫자가 공백 없이 쓰여있다. 이 숫자를 모두 합해서 출력하는 프로그램을 작성하시오.
입력
첫째 줄에 숫자의 개수 N (1 ≤ N ≤ 100)이 주어진다. 둘째 줄에 숫자 N개가 공백 없이 주어진다.
출력
입력으로 주어진 숫자 N개의 합을 출력한다.
예제 입력 1 복사
1
1
예제 출력 1 복사
1
예제 입력 2 복사
5
54321
예제 출력 2 복사
15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int total = 0;
int N = sc.nextInt();
String s = sc.next();
sc.close();
for (int i =0; i < N; i++) {
total += Integer.parseInt(s.substring(i, i+1));
}
System.out.println(total);
}
|
cs |
개선
BufferedReader: scanner 보다 빠르다.
Integer.parseInt: int로 변환해주었다.
String.valueOf: char에서 string으로 바꿔준다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int input = Integer.parseInt(br.readLine());
char[] numbers = br.readLine().toCharArray();
int total = 0;
for (int i=0; i<input; i++){
total += Integer.parseInt(String.valueOf(numbers[i]));
}
System.out.println(total);
}
}
|
cs |
'코딩 문제 > 백준 [ Java ]' 카테고리의 다른 글
[ 백준 14888 / Java ] 연산자 끼워넣기 - 삼성 SW 역량 테스트 기출 문제 (0) | 2022.06.09 |
---|---|
[ 백준 2753 / Java ] 윤년 (0) | 2022.06.08 |
[ 백준 9205 / Java ] 맥주 마시면서 걸어가기 (0) | 2022.02.23 |
[ 백준 18352 / Java ] 특정 거리의 도시 찾기 (0) | 2022.02.22 |
[ 백준 11060 / Java ] 점프 점프 (0) | 2022.02.19 |
댓글