-
4. x만큼 간격이 있는 n개의 숫자코딩 테스트/Level 1 2019. 10. 2. 20:07반응형
https://programmers.co.kr/learn/courses/30/lessons/12954
코딩테스트 연습 - x만큼 간격이 있는 n개의 숫자
함수 solution은 정수 x와 자연수 n을 입력 받아, x부터 시작해 x씩 증가하는 숫자를 n개 지니는 리스트를 리턴해야 합니다. 다음 제한 조건을 보고, 조건을 만족하는 함수, solution을 완성해주세요.
programmers.co.kr
파이썬
깔끔하긴 하지만 x가 0이나 음수일 때 작동하지 않습니다.
def solution(x, n): return list(range(x, x*n+1, x))
이렇게 하면 잘 작동 되겠죠? 하지만 복잡합니다.
def solution(x, n): return list(map(lambda i : x * i, range(1, n + 1)))
리스트 컴프리헨션을 이용하는 게 가장 좋아보입니다.
def solution(x, n): return [i * x for i in range(1, n + 1)]
자바스크립트
function solution(x, n) { let answer = [] for (let i = 1; i <= n; i++) { answer.push(i * x) } return answer; }
자바
class Solution { public long[] solution(long x, int n) { long[] answer = new long[n]; for (int i = 0; i < n; i++) { answer[i] = (i + 1) * x; } return answer; } }
고
func solution(x int, n int) (answer []int64) { for i := 1; i <= n; i++ { answer = append(answer, int64(i*x)) } return }
곱하기 보다 더하기가 좀 더 효율적이려나?
func solution(x, n int) (answer []int64) { answer = append(answer, int64(x)) for i := 0; i < n-1; i++ { answer = append(answer, answer[i]+int64(x)) } return }
코틀린
class Solution { fun solution(x: Int, n: Int): LongArray { var numList = mutableListOf<Long>() for (i in 1..n) { numList.add(i.toLong() * x) } return numList.toLongArray() } }
class Solution { fun solution(x: Int, n: Int) = LongArray(n) { x.toLong() * (it + 1) } }
C#
public class Solution { public long[] solution(int x, int n) { long[] answer = new long[n]; for (int i=0; i < n; i++) answer[i] = (long)x * (i + 1); return answer; } }
DART
List<int> solution(int a, int b) { List<int> arr = []; for (int i = 1; i < b + 1; i++) { arr.add(i * a); } return arr; }
반응형