알고리즘 풀이 방법입니다.
문제(Problem) -> 생각(Think) -> 해결책(Solution) -> 리뷰(Review) 를 통해서 정리해서 작성합니다.
Problem📄
https://level.goorm.io/exam/48757/369-%EA%B2%8C%EC%9E%84/quiz/1
구름LEVEL
코딩테스트에서 가장 높은 비중을 차지하는 알고리즘 문제를 제작하고 풀이할 수 있는 온라인 저지 서비스입니다. 기업에서 선호하는 C, C++, 파이썬(Python), 자바(Java), 자바스크립트(Javascript) 이
level.goorm.io
Think🤔
숫자 N이 주어졌을 때 3이 몇번 나왔는지 구하는 문제
만약 33이면 박수를 두번 쳐야함
그러면 이건 나눗셈을 이용하지 않고, 문자로 판별해야한다.
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
int numInput = Integer.parseInt(input);
int answer = 0;
for(int i=2; i<=numInput; i++){
for(int j=0; j<input.length(); j++){
String strI = String.valueOf(i);
if(strI.charAt(j) == '3' || strI.charAt(j) == '6' || strI.charAt(j) == '9'){
answer++;
}
}
}
System.out.print(answer);
}
}
어느게 잘못된 것일까..?
String index out of range : 1 이 나오는데
배열의 길이를 넘어다는것이다.
charAt은 0부터 검사한다는 것으로 알고있는데
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
int numInput = Integer.parseInt(input);
int answer = 0;
for(int i=2; i<numInput; i++){
String strI = String.valueOf(i);
for(int j=0; j<strI.length(); j++){
if(strI.charAt(j) == '3' || strI.charAt(j) == '6' || strI.charAt(j) == '9'){
answer++;
}
}
}
System.out.print(answer);
}
}
코드를 보니 안의 for문을 돌때 br.readLine으로 받은 값은 한번만 생성되고 없어지는 것 같다?
아마 가비지 컬렉터에 의해 그 값을 읽고 바로 없어지므로 변수에 담아서 그 변수의 length() 만큼 돌려주는 것이 맞는 코드인 것 같다.
Solution✍
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
int numInput = Integer.parseInt(input);
int answer = 0;
for(int i=2; i<numInput; i++){
String strI = String.valueOf(i);
for(int j=0; j<strI.length(); j++){
if(strI.charAt(j) == '3' || strI.charAt(j) == '6' || strI.charAt(j) == '9'){
answer++;
break;
}
}
}
System.out.print(answer);
}
}
Review🤩
다시보니 readLine을 못읽는게 아니다. 따로 테스트 해보니깐 readLine은 생성되고 없어지는게 아니였다.
다만 i가 2로 시작할때 처음에 입력값을 35라고 해서 그 만큼 검사하는데 35는 길이가 2이고 처음 반복문이 시작하는 2는 문자열 길이가 1이기 때문이다!
'Algorithm' 카테고리의 다른 글
[구름] Substring (0) | 2021.12.25 |
---|---|
[구름] Bubble Sort (0) | 2021.12.25 |
[구름] 시험성적 평균과 등급 구하기 (0) | 2021.12.25 |
[구름] 약수 구하기 (0) | 2021.12.25 |
[구름] 3과 5의 배수 (0) | 2021.12.25 |