alorithm/programmers

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

Hannana. 2023. 4. 11. 04:17
반응형

[문제]

 

 

[나의 풀이]

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

    public static void main(String[] args){
        Solution solution = new Solution();
    }
}

 

 

[다른사람의 풀이 Ⅰ] 

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;

    }
}

 

 [다른사람의 풀이 Ⅱ]

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

 

 

 

1은 직관적이며 심플하고 2는 애초에 long 형태로 인자 값을 받은 게 인상적이었다.

코드를 최대한 줄이는 연습을 해봐야겠다.

 

 

반응형