https://programmers.co.kr/learn/courses/30/lessons/12954#
코드 1 (테스트케이스 13, 14 실패)
class Solution {
public long[] solution(int x, int n) {
long[] answer = new long[n];
answer[0] = x;
for(int i=1; i<n ; i++){
answer[i] = x*(i+1);
}
return answer;
}
}
x, i 모두 int형
int형 * int형 =int형 이라 overflow가 발생하며, 이후 long에 저장하면 값이 변형될 수 있다.
따라서 x를 long형으로 형변환하면 가능하다.
코드 1 (통과)
class Solution {
public long[] solution(int x, int n) {
long[] answer = new long[n];
answer[0] = x;
for(int i=1; i<n; i++){
answer[i] = (long)x * (i+1);
}
return answer;
}
}
코드 2 (통과)
class Solution {
public long[] solution(int x, int n) {
long[] answer = new long[n];
int idx = 0;
answer[idx++] = x;
while(idx<n){
answer[idx] = answer[idx-1]+x;
idx++;
}
return answer;
}
}
answer[idx-1] (long형) + x(int형) 이라 정상 실행
'Preparing Coding Test > Programmers L1' 카테고리의 다른 글
[Java] 수박수박수박수박수박수? (0) | 2020.07.21 |
---|---|
[Java] 문자열 다루기 기본 (0) | 2020.07.21 |
[Java] 문자열 내림차순으로 배치하기 (0) | 2020.07.17 |
[Java] 두 정수 사이의 합 (0) | 2020.07.14 |
[Java] 가운데 글자 가져오기 (0) | 2020.07.14 |