728x90
<정답>
import java.io.*;
public class Main{
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
String s = br.readLine();
int sum = 0;
for(int i=0;i<N;i++){
sum += s.charAt(i) - 48;
}
System.out.print(sum);
}
}
48을 빼주는 이유는 s.charAt()은 여전히 문자인데 내가 원하는 건 int이기 때문에 '0'의 아스키코드(48)만큼 빼줘서 int 형태로 바꾼다. 48 대신 '0'을 빼줘도 된다.
sum += s.charAt(i) -'0';
반응형
'알고리즘 > 백준' 카테고리의 다른 글
[백준 / 입출력] 2741 : N 찍기 (Java) (0) | 2023.09.02 |
---|---|
[백준 / 입출력] 11721 : 열 개씩 끊어 출력하기 (Java) (0) | 2023.09.02 |
[백준 / 입출력] 11719 : 그대로 출력하기 2 (Java) (0) | 2023.09.02 |
[백준 / 입출력] 11718 : 그대로 출력하기 (Java) (0) | 2023.09.02 |
[백준 / 입출력] 11022 : A+B - 8 (Java) (0) | 2023.09.02 |