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

yewon Lee·2026년 1월 23일

프로그래머스

목록 보기
1/3

link: 코딩테스트 연습 - x만큼 간격이 있는 n개의 숫자

1. 배열 long[] 사용

주의할 점

  • 배열에 크기를 미리 지정해주어야 함

    long[] answer = new long[n];
  • add() 사용 불가능 - add()는 ArrayList에 있는 함수이다.

  • long타입 지정해주기

    answer[i] = (long)x*(i+1);
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;
    }
}

add를 사용하기 위해 2번으로

2. ArrayList<> 사용

주의할 점

  • 프로그래머스는 이미 지정된 타입이 있기 때문에 타입 변경이 필요함

    long[] answer = new long[n];
            for(int i = 0; i < n; i++){
                answer[i] = list.get(i);
            } 
  • ArrayList<> 타입을 쓸 때는 대문자!

    ArrayList<Long> list = new ArrayList<>();
  • int를 long 타입으로 변경해주기

    list.add((long)x*(i+1));
  • import java.util.*; 추가 해주기

    import java.util.*;
import java.util.*;

class Solution {
    public long[] solution(int x, int n) {
        ArrayList<Long> list = new ArrayList<>();
        
        
        for(int i = 0; i < n; i++){
            list.add((long)x*(i+1));
        }
        
        long[] answer = new long[n];
        for(int i = 0; i < n; i++){
            answer[i] = list.get(i);
        }
        
        return answer;
    }
}
profile
시작

0개의 댓글