문제

로직
배열 크기, 결과 변수 선언
배열 선언 및 크기 설정
배열 크기 제한
readLine을 통해 한줄로 문자열 입력 받음
반복문
- 문자열의 한자리씩 정수로 변환 후 배열에 삽입
- 결과 변수에 총합 계산
결과 변수 출력
My Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
int result = 0;
int arraySize = 1;
Scanner sc = new Scanner(System.in);
arraySize = sc.nextInt();
int[] intArray = new int[arraySize];
if (intArray.length<=100 && intArray.length>=1){
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str = reader.readLine();
for(int i = 0; i < intArray.length; i++) {
intArray[i] = Integer.valueOf(str.substring(i, i+1));
result += intArray[i];
}
}catch (Exception e) {}
System.out.print(result);
}
}
}
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
int result = 0;
int arraySize = 1;
Scanner sc = new Scanner(System.in);
arraySize = sc.nextInt();
int[] intArray = new int[arraySize];
if (intArray.length<=100 && intArray.length>=1){
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str = reader.readLine();
for(int i = 0; i < intArray.length; i++) {
intArray[i] = Integer.valueOf(str.substring(i, i+1));
result += intArray[i];
}
}catch (Exception e) {}
System.out.print(result);
}
}
}
결과

결과는 모든 백준 예시와 동일하나 "틀렸습니다."라고 뜨는 걸 보니 범위 문제가 있었다...
앞으로는 문제에 주어진 범위를 잘 확인해서 자료형을 선택해야겠다.
문제의 핵심 & 알게된 점
정수가 아닌 String으로 숫자 N개를 입력받고 문자열 char변환해서 배열 형식으로 저장
char형을 정수형으로 바꾸면 아스키코드 값으로 바뀜 -> 1을 아스키코드 값으로 바꾸면 49
따라서 '1' - 48 또는 '1' - '0'으로 해야 1값이 나옴
readLine()을 통해 한 줄로 문자를 받아야겠다고 생각했으나
어차피 문자는 한줄로 길게 받고
배열로 한 자릿 수씩 볼 수 있는데 너무 복잡하게 생각한 것 같다.
주어진 문제 내용에 따라 자료형, 범위를 고려해야겠다.
강의 Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
String sNum = sc.next();
char[] cNum = sNum.toCharArray();
int sum = 0;
for (int i = 0; i<cNum.length; i++) {
sum += cNum[i] - '0';
}
System.out.println(sum);
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
String sNum = sc.next();
char[] cNum = sNum.toCharArray();
int sum = 0;
for (int i = 0; i<cNum.length; i++) {
sum += cNum[i] - '0';
}
System.out.println(sum);
}
}
*참고 강의_인프런의 Do it! 알고리즘 코딩테스트 with JAVA
Do it! 알고리즘 코딩테스트 with JAVA
'Java' 카테고리의 다른 글
[백준] 12891번 DNA 비밀번호 - 슬라이딩 윈도우 / switch / 함수 (0) | 2023.08.12 |
---|---|
[백준] 1940번 주몽 - 투포인터 / 시간 제한 맞추기 / 배열 정렬 / BufferReader (0) | 2023.08.12 |
[백준] 2018번 수들의 합5 - 투포인터 / 배열 / if문 / while문 (0) | 2023.08.11 |
[백준] 11659번 구간 합 구하기4 - 구간 합 / 배열 / BufferedReader / StringToken (0) | 2023.08.09 |
[백준]1546번 평균 - 배열 / 정수에서 실수로 변환 / 반복문 (0) | 2023.08.09 |