[프로그래머스/자바] x만큼 간격이 있는 n개의 숫자

솔솔·2022년 12월 27일
0
post-thumbnail

📑 문제 설명

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



🧑🏻‍💻 문제 풀이

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



🧑🏻‍💻 다른 사람의 풀이

import java.util.*;
class Solution {
    public static long[] solution(int x, int n) {
        long[] answer = new long[n];
        answer[0] = x;

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

나처럼 long 변수에 x를 대입하지 않고 바로 answer[0]에 x를 대입해 훨씬 간결하게 풀이했다.



🔗 문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/12954

0개의 댓글