anothel의 지식 창고

연습문제 > x만큼 간격이 있는 n개의 숫자 본문

연습장

연습문제 > x만큼 간격이 있는 n개의 숫자

anothel 2021. 11. 27. 10:44

문제 설명

함수 solution은 정수 x와 자연수 n을 입력받아, x부터 시작해 x씩 증가하는 숫자를 n개 지니는 리스트를 리턴해야 합니다. 다음 제한 조건을 보고, 조건을 만족하는 함수, solution을 완성해주세요.

제한 조건

  • x는 -10000000 이상, 10000000 이하인 정수입니다.
  • n은 1000 이하인 자연수입니다.

입출력 예

x n answer
2 5 [2,4,6,8,10]
4 3 [4,8,12]
-4 2 [-4, -8]

 

Solution

#include <string>
#include <vector>

using namespace std;

vector<long long> solution(int x, int n) {
    vector<long long> answer;
    for(int i = 1; i <= n; i++) answer.push_back(x * i);
    return answer;
}

 

남의 코드

#include <string>
#include <vector>

using namespace std;

vector<long long> solution(int x, int n) {
    vector<long long> answer(n, x);

    for (int i = 1; i < n; i++)
        answer[i] = answer[i - 1] + x;

    return answer;
}

 

후기

가볍게 넘길 수도 있었던 문제였으나, 수가 충분히 컸을 때를 고려했어야 하는 문제였다.

 

(url: https://programmers.co.kr/learn/courses/30/lessons/12954)

 

728x90