본문 바로가기

알고리즘/백준

[백준 / 입출력] 11720 : 숫자의 합 (Java)

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';

 

 

 

반응형