출처:
class Solution {
public long[] solution(int x, int n) {
long[] answer = new long[n];
// 등차 수열인데
// a = a + (n - 1) * d; 이렇게 되어야 함
// 여기서 a = x, d = x 임
for(int i = 0; i < answer.length; i++){
answer[i] = x + ((i + 1) - 1) * x;
}
return answer;
}
}
채점 결과
정확성: 85.7
합계: 85.7 / 100.0
왜그럴까?
x가 -1억 ~ 1억 범위 내의 int형이라고 해도, x * i의 결과는 long 범위가 필요할 수 있다.
Java에서 int * int 연산은 int형으로 계산된 후 long에 대입되기 때문에 오버플로우가 발생할 수 있다.
x + (i x) → x (i + 1)로 바꾸고
x를 long으로 캐스팅해서 곱해야 함: (long)x * (i + 1)
요구사항 만족하는 코드문
class Solution {
public long[] solution(int x, int n) {
long[] answer = new long[n];
// 등차 수열인데
// a = a + (n - 1) * d; 이렇게 되어야 함
// 여기서 a = x, d = x 임
for(int i = 0; i < n; i++){
answer[i] = (long)x * (i + 1);
}
return answer;
}
}
다른 사람의 풀이
import java.util.*;
class Solution {
public static long[] solution(int x, int n) {
long[] answer = new long[n];
answer[0] = x;
for (int i = 1; i < n; i++) {
answer[i] = answer[i - 1] + x;
}
return answer;
}
}
class Solution {
public long[] solution(int x, int n) {
long[] answer = new long[n];
long sum = 0;
for(int i = 0;i<answer.length;i++){
sum += x;
answer[i] = sum;
}
return answer;
}
}