본문 바로가기

Study/Programmers

[Programmers] 프로그래머스 문제풀이 x만큼 간격이 있는 n개의 숫자

정말 쉬우니 한 번 스스로 풀어보는 것을 권장합니다.
문제는 여기서 풀어볼 수 있습니다.

문제 설명

함수 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]

풀이

JavaScript

function solution(x, n) {
    return Array(n).fill(x).map((v, i) => (i + 1) * v)
}

Python

def solution(x, n):
    return [i * x + x for i in range(n)]

Java

class Solution {
  public long[] solution(long x, int n) {
      long[] answer = new long[n];
      for(int i = 0; i < n; i++){
          answer[i] = x * (i + 1);
      }
      return answer;
  }
}

C++

#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;
}

Go

func solution(x int, n int) []int64 {
    var result []int64
    for i := 0 ; i < n; i++ {
        result = append(result, int64(x+x*i))
    }
    return result
}

Kotlin

class Solution {
    fun solution(x: Int, n: Int): LongArray = LongArray(n) { x.toLong() * (it + 1) }
}