[프로그래머스] Lv.0 배열의 길이를 2의 거듭제곱으로 만들기.java

hgghfgf·2023년 6월 11일
0

프로그래머스

목록 보기
142/227

배열의 길이를 2의 거듭제곱으로 만들기.java

import java.util.Arrays;

class Solution {
    public int[] solution(int[] arr) {
        int n = arr.length;
        int targetLength = 1;
        
        // targetLength가 n보다 작거나 같은 2의 거듭제곱을 찾음
        while (targetLength < n) {
            targetLength *= 2;
        }
        
        // 0을 추가하여 targetLength 길이의 배열 생성
        int[] answer = new int[targetLength];
        Arrays.fill(answer, 0);
        
        // arr의 요소들을 answer로 복사
        System.arraycopy(arr, 0, answer, 0, n);
        
        return answer;
    }
}

주어진 배열 arr의 길이 n을 구합니다.
2의 거듭제곱인 targetLength를 1로 초기화합니다.
targetLength가 n보다 작거나 같은 2의 거듭제곱을 찾을 때까지 targetLength를 2배씩 증가시킵니다.
0으로 초기화된 targetLength 길이의 새로운 배열 answer를 생성합니다.
arr의 요소들을 answer로 복사합니다.
answer를 반환합니다.

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

0개의 댓글