본문 바로가기
알고리즘/[프로그래머스] JAVA

[코딩 기초 트레이닝] 배열의 길이를 2의 거듭제곱으로 만들기

by 코딩맛집 2024. 2. 5.

문제 :

https://school.programmers.co.kr/learn/courses/30/lessons/181857

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

해결 :

import java.util.*;

class Solution {
    public int[] solution(int[] arr) {
        int length = 1;

        while (length < arr.length) {
            length *= 2;
        }

        return Arrays.copyOf(arr, length);
    }
}

 

다른 사람 풀이 :

class Solution {
    public int[] solution(int[] arr) {
        int length = arr.length;
        
        if (length == 1) {
            return arr;
        }
        
        int x = 0;
        int y = 0;
        int len = arr.length;
        
        while (len > x) {
            x = (int) Math.pow(2, y++);
        }
        
        int[] answer = new int[x];
        for (int i = 0; i < arr.length; i++) {
            answer[i] = arr[i];
        }
        
        return answer;
    }
}

 

[길이가 거듭 제곱인지 알 수 있는 방법]

- 짝수를 계속 2로 나눴을 때, 1이 되면 그 수는 2의 거듭제곱이다.

- Math.pow(대상 숫자, 지수)메소드의 입력값과 출력값은 double이다. 

public class Pow {
    public static void main(String[] args)  {

        double result = Math.pow(2, 2); //2의제곱
        System.out.println("2의 제곱은 : "+result);
    }
}

 

참고 : https://tiny-stone.com/317