[프로그래머스] Lv.0 n 번째 원소까지.java

hgghfgf·2023년 4월 25일
0

프로그래머스

목록 보기
9/227

n 번째 원소까지.java

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

먼저 answer 배열을 초기화하기 위해 int[] answer = new int[n]으로 길이가 n인 배열을 생성합니다.
그리고 for 루프를 이용하여 num_list의 첫 n개 요소를 answer 배열에 복사합니다. answer[i] = num_list[i] 라인에서 i는 0에서 시작하여 n-1까지 반복됩니다.
마지막으로 answer 배열을 반환합니다.

출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges

0개의 댓글