Lv.1 x만큼 간격이 있는 n개의 숫자

서현우·2022년 4월 22일
0

알고리즘 풀이

목록 보기
12/31

문제 설명

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

초기코드

class Solution {
    public long[] solution(int x, int n) {
        long[] answer = {};
        return answer;
    }
}

내 풀이

//long타입 배열 answer 선언과 생성
//answer[0]~answer[n-1]에 
//(i+1L)*x를 대입

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

다른 풀이 1

//배열 선언과 생성.
//answer[0]에 x를 대입.
//answer[1]부터 answer[0]+x 이런식으로 //answer[i]에 값을 대입


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;

    }
}

다른 풀이 2

//long타입 배열 선언과 생성
//변수 sum 선언
//sum에 x를 더해나가고, sum을 answer[i]에 대입.


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


      return answer;
  }
}
profile
안녕하세요!!

0개의 댓글