https://school.programmers.co.kr/learn/courses/30/lessons/120924
등차수열 혹은 등비수열 common
이 매개변수로 주어질 때, 마지막 원소 다음으로 올 숫자를 return 하도록 solution 함수를 완성해보세요.
2 < common의 길이 < 1,000
-1,000 < common의 원소 < 2,000
common의 원소는 모두 정수입니다.
등차수열 혹은 등비수열이 아닌 경우는 없습니다.
등비수열인 경우 공비는 0이 아닌 정수입니다.
common | result |
---|---|
[1, 2, 3, 4] | 5 |
[2, 4, 8] | 16 |
[1, 2, 3, 4]는 공차가 1인 등차수열이므로 다음에 올 수는 5이다.
[2, 4, 8]은 공비가 2인 등비수열이므로 다음에 올 수는 16이다.
class Solution {
public int solution(int[] common) {
int answer = 0;
int len=common.length;
if(common[1]-common[0]==common[2]-common[1]){//등차수열
int gap=common[1]-common[0];
answer=common[len-1]+gap;
}
else if((double)(common[1]/common[0])==(double)(common[2]/common[1])){//등비수열
int gop=common[1]/common[0];
answer=common[len-1]*gop;
}
return answer;
}
}
등차
수열이면 그 간격을 마지막 원소 값에 더해주고,
등비
수열이면 그 공비를 마지막 원소 값에 곱해주면 된다.