티스토리 뷰

코딩테스트 연습 - 다음에 올 숫자

문제 설명


등차수열 혹은 등비수열 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

  • [1, 2, 3, 4]는 공차가 1인 등차수열이므로 다음에 올 수는 5이다.

입출력 예 #2

  • [2, 4, 8]은 공비가 2인 등비수열이므로 다음에 올 수는 16이다.

제출 코드


2023년 1월 30일

#include <string>
#include <vector>

using namespace std;

int solution(vector<int> common) {
    int answer = 0;
    int length = common.size();
    int ratio = 0;

    if (common[2] - common[1] != common[1] - common[0])
    {
        ratio = common[2] / common[1];
        return answer = common.back() * ratio;
    }
    else
    {
        ratio = common[1] - common[0];
        return answer = common.back() + ratio;
    }
}

등비 수열의 경우 원소의 차가 다 다를 수 밖에 없으므로 해당 코드로 분기점을 골랐다.

📕 오답 노트

#include <string>
#include <vector>

using namespace std;

int solution(vector<int> common) {
    int answer = 0;
    int length = common.size();
    int ratio = 0;
    bool isGS = false;

    if (common[0] * common[1] == common[2] && common[2] - common[1] != common[1] - common[0])
    {
        isGS = true;
        ratio = common[2] / common[1];
    }
    else
    {
        isGS = false;
        ratio = common[1] - common[0];
    }

    isGS == true ? answer = common[length - 1] * ratio : answer = common[length - 1] + ratio;

    return answer;
}

테스트 케이스 4번, 9번 오류

예를 들어 common = { 1, 2, 4 }; 라고 한다면 첫번째 분기문에 허용되지 않기 때문에 등차수열을 구하는 else문으로 들어간다.

#include <string>
#include <vector>

using namespace std;

int solution(vector<int> common) {
    int answer = 0;
    int length = common.size();
    int ratio = 0;
    bool isGS = false;

    if (common[0] * common[1] == common[2] || common[2] - common[1] != common[1] - common[0])
    {
        isGS = true;
        ratio = common[2] / common[1];
    }
    else
    {
        isGS = false;
        ratio = common[1] - common[0];
    }

    isGS == true ? answer = common[length - 1] * ratio : answer = common[length - 1] + ratio;

    return answer;
}

그래서 다음에는 이렇게 작성했는데, 원소 중에 0이 있을 경우 0으로 무언가를 나눌 때 문제가 됐을 것이라고 Q&A에 올라왔다.

6번 케이스 틀림 : 실패 (signal : floating point exception (core dumped))

간단히 만들 수 있었던 점

반환해줘야 하는 값이 answer이고, isGS가 없어도 해당 분기문으로 2가지를 구분할 수 있기 때문에 isGS를 없애주었고 분기문 끝날 때 바로 반환해주도록 했다.

 

 

'😈 알고리즘 > 🖥️ 프로그래머스' 카테고리의 다른 글

🖥️ 옹알이 (1)  (0) 2023.03.02
🖥️ 분수의 덧셈  (0) 2023.03.01
🖥️ 다항식 더하기  (0) 2023.02.27
🖥️ 저주의 숫자 3  (0) 2023.02.17
🖥️ 특이한 정렬  (0) 2023.02.16
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
링크
Total
Today
Yesterday