프로그래머스
프로그래머스 - x만큼 간격이 있는 n개의 숫자
thiago6
2019. 1. 8. 15:43
내 코드 - 오답
class Solution {
public long[] solution(int x, int n) {
long[] answer = {};
answer = new long[n];
for (int i = 0; i < n; i++) {
/**
* 여기서 answer[i]에는 int가 들어감
*
* 따라서 만약,
* x * (i + 1)이 int 범위를 초과한다면 엉뚱한 값이 들어감
*/
answer[i] = x * (i + 1);
}
return answer;
}
}
문제에서 -10,000,000 <= x <= 10,000,000 이고,
int형 변수의 범위는 -2,147,483,648 ~ 2,147,483,647 이다.
따라서 가령,
x = 10,000,000, n = 1,000 이라면
x * (i + 1) = 10,000,000 * 1,000 = 10,000,000,000 와 같이 int형 범위를 초과하게 된다.
아래와 같이 long 타입으로 변환시켜 주어야 한다.
class Solution {
public long[] solution(int x, int n) {
long[] answer = {};
answer = new long[n];
for (int i = 0; i < n; i++) {
answer[i] = Long.valueOf(x) * (i + 1);
}
return answer;
}
}