문제
Note
숫자 type 주의, long type을 잘 쓰자. 오늘은 type이 문제일 것을 빨리 찾아냄.
문자열을 숫자로 바꿔 줄 때 메소드에서의 숫자 타입도 신경쓰자.
Key
Long.parseLong();
str.substring(a);
str.substring(a,b);
제출한 코드
처음 제출한 코드는 일부 런타임 에러가 떠서 틀렸다.
다시 잘 보니 기껏 long으로 선언했던 배열 인자를 Integer로 가져오고 있는 모습 발견
import java.util.*;
class Solution {
public int solution(String t, String p) {
int answer = 0;
int pleng = p.length(); //p길이
int arrleng = t.length() - pleng + 1; //substring 담은 배열의 길이
long[] strArr = new long[arrleng]; //substring을 int로 담은 배열
long pval = Integer.valueOf(p);
//t를 p길이만큼 자른 문자열 배열
//배열 인자들 숫자로 변환
for(int i =0; i<arrleng ; i++){
strArr[i] = Integer.valueOf(t.substring(i,i+pleng));
}
//배열 인자들을 p와 비교
for(int i=0;i<arrleng;i++){
if(pval >= strArr[i] ) answer++;
}
return answer;
}
}
다시 long으로 파싱하기
import java.util.*;
class Solution {
public int solution(String t, String p) {
int answer = 0;
int pleng = p.length(); //p길이
int arrleng = t.length() - pleng + 1; //substring 담은 배열의 길이
long[] strArr = new long[arrleng]; //substring을 int로 담은 배열
long pval = Long.parseLong(p);
//t를 p길이만큼 자른 문자열 배열
//배열 인자들 숫자로 변환
//배열 인자들을 p와 비교
for(int i =0; i<arrleng ; i++){
strArr[i] = Long.parseLong(t.substring(i,i+pleng));
if(pval >= strArr[i] ) answer++;
}
return answer;
}
}
반응형