🧩 Programming Languages/Java CodingTest
12954. x만큼 간격이 있는 n개의 숫자
복숭아아이스티에샷추가
2025. 2. 14. 11:00
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
[ 1차 답안 제출 ]
class Solution {
public long[] solution(int x, int n) {
long[] answer = new long[n];
for (int i = 0; i < n; i++) {
answer[i] = x;
x += x;
}
return answer;
}
}
[ 2차 답안 제출 ]
class Solution {
public long[] solution(int x, int n) {
long[] answer = new long[n];
for (int i = 0; i < n; i++) {
answer[i] = x * (i + 1);
}
return answer;
}
}
[ 3차 답안 제출 ]
기본적으로 x와 i + 1은 int 타입이기 때문에 두 수를 곱해도 int 타입이 나온다.
하지만 x는 -10,000,000 이상, 10,000,000 이하인 정수이므로 만약 최대 값인 10,000,000 이고, n이 1,000 라면?
x * n = 10,000,000,000가 되어 int 타입의 범위 -2,147,483,648 ~ 2,147,483,647 를 벗어나게 되는 상황이 존재한다.
이러한 오버플로우 현상을 막기 위해 명시적으로 long 타입으로 변환시켜줘야한다!
class Solution {
public long[] solution(int x, int n) {
long[] answer = new long[n];
for (int i = 0; i < n; i++) {
answer[i] = (long) x * (i + 1);
}
return answer;
}
}