Home [C++ 프로그래머스] 다음에 올 숫자
Post
Cancel

[C++ 프로그래머스] 다음에 올 숫자

문제 링크

 프로그래머스

1. 문제 설명

등차수열 혹은 등비수열 common이 매개변수로 주어질 때, 마지막 원소 다음으로 올 숫자를 return 하도록 solution 함수를 완성해보세요.

제한 사항

  • 2 < common의 길이 < 1,000
  • -1,000 < common의 원소 < 2,000
    • common의 원소는 모두 정수입니다.
  • 등차수열 혹은 등비수열이 아닌 경우는 없습니다.
  • 등비수열인 경우 공비는 0이 아닌 정수입니다.

입출력 예

commonresult
[1, 2, 3, 4]5
[2, 4, 8]16

2. 풀이 방법

  • 등차 수열 - 동일한 값으로 더해지는 수열
  • 등비 수열 - 동일한 값으로 곱해지는 수열

제한 사항에서 common의 길이는 최소 3 이상이기 때문에 

1
(common[2] - common[1]) == (common[1] - common[0])

이면 등차 수열 아니면 등비 수열로 볼 수 있다.

3. 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <vector>

using namespace std;

int solution(vector<int> common)
{
    int answer = 0;

    int index0 = common[0];
    int index1 = common[1];
    int index2 = common[2];

    if ((index2 - index1) == (index1 - index0))
        return common[common.size() - 1] + (index1 - index0);
    else
        return common[common.size() - 1] * (index2 / index1);
}
This post is licensed under CC BY 4.0 by the author.