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[] str = br.readLine().split("");
int sum = 0;
for (int i = 0; i < n; i++) {
sum += Integer.parseInt(str[i]);
}
System.out.print(sum);
}
}
불필요한 split()
n 변수 미사용
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 str = br.readLine();
int sum = 0;
for (int i = 0; i < n; i++) {
sum += str.charAt(i) - '0';
}
System.out.print(sum);
}
}
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine(); // n은 사용 안 함
char[] chars = br.readLine().toCharArray();
int sum = 0;
for (char c : chars) {
sum += c - '0';
}
System.out.print(sum);
}
}
| 방법 | 메모리 | 시간 | 특징 |
|---|---|---|---|
| split() | 14404KB | 104ms | 배열 생성 |
| charAt() | 14200KB | 100ms | 더 빠름 |
| toCharArray() | 14200KB | 100ms | for-each 가능 |
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 str = br.readLine();
int sum = 0;
for (int i = 0; i < n; i++) {
sum += str.charAt(i) - '0';
}
System.out.print(sum);
}
}
핵심: '0'을 빼면 숫자로 변환 (ASCII 이용)
문자를 숫자로 변환:
'5' - '0' = 5charAt()이 split() + parseInt()보다 빠름#백준 #문자열 #charAt #Bronze4 #ASCII