Preparing Coding Test/Programmers L1
[Java] x만큼 간격이 있는 n개의 숫자
weero
2020. 7. 21. 19:05
https://programmers.co.kr/learn/courses/30/lessons/12954#
코딩테스트 연습 - x만큼 간격이 있는 n개의 숫자
함수 solution은 정수 x와 자연수 n을 입력 받아, x부터 시작해 x씩 증가하는 숫자를 n개 지니는 리스트를 리턴해야 합니다. 다음 제한 조건을 보고, 조건을 만족하는 함수, solution을 완성해주세요. ��
programmers.co.kr
코드 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형) 이라 정상 실행