코딩 테스트 (Java)/코딩 기초 트레이닝 (프로그래머스)

181881. 조건에 맞게 수열 변환하기 2

가지코딩 2025. 4. 17. 14:06

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


문제

정수 배열 arr가 주어집니다. arr의 각 원소에 대해 값이 50보다 크거나 같은 짝수라면 2로 나누고, 50보다 작은 홀수라면 2를 곱하고 다시 1을 더합니다.

이러한 작업을 x번 반복한 결과인 배열을 arr(x)라고 표현했을 때, arr(x) = arr(x + 1)x가 항상 존재합니다. 이러한 x 중 가장 작은 값을 return 하는 solution 함수를 완성해 주세요.

단, 두 배열에 대한 "="는 두 배열의 크기가 서로 같으며, 같은 인덱스의 원소가 각각 서로 같음을 의미합니다.

 

제한사항

  • 1 ≤ arr의 길이 ≤ 1,000,000
    • 1 ≤ arr의 원소의 값 ≤ 100

 

입출력 예

arr result
[1, 2, 3, 100, 99, 98] 5

 

  • 위 작업을 반복하면 다음과 같이 arr가 변합니다.
반복 횟수 arr
0 [1, 2, 3, 100, 99, 98]
1 [3, 2, 7, 50, 99, 49]
2 [7, 2, 15, 25, 99, 99]
3 [15, 2, 31, 51, 99, 99]
4 [31, 2, 63, 51, 99, 99]
5 [63, 2, 63, 51, 99, 99]
6 [63, 2, 63, 51, 99, 99]
  • 이후로 arr가 변하지 않으며, arr(5) = arr(6)이므로 5를 return 합니다.

풀이

import java.util.Arrays;

class Solution {
    public int solution(int[] arr) {
        int[] a = arr.clone();
        int[] b = new int[arr.length];
        
        int i=0;
        while(true){
            b = fun(a);
            if(Arrays.equals(a, b)){
                break;
            }
            a = b;
            i++;
        }
        return i;
    }
    
    public int[] fun(int[] arr) {
        int[] answer = arr.clone();
        
        for(int i=0; i<answer.length; i++){
            if(answer[i] >= 50 && answer[i]%2 == 0){
                answer[i] /= 2;
            } else if(answer[i] < 50 && answer[i]%2 == 1){
                answer[i] = answer[i]*2 + 1;
            }
        }
        return answer;
    }
}

 


이전 문제(https://gajicoding.tistory.com/161)의 답을 함수로 구현하여 사용했다.

조건이 조금 달라졌으니 주의

answer[i] = answer[i]*2 + 1;

GitHub: https://github.com/gajicoding/coding_test/edit/main/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4/0/181881.%E2%80%85%EC%A1%B0%EA%B1%B4%EC%97%90%E2%80%85%EB%A7%9E%EA%B2%8C%E2%80%85%EC%88%98%EC%97%B4%E2%80%85%EB%B3%80%ED%99%98%ED%95%98%EA%B8%B0%E2%80%852

 

coding_test/프로그래머스/0/181881. 조건에 맞게 수열 변환하기 2 at main · gajicoding/coding_test

This is an auto push repository for Baekjoon Online Judge created with [BaekjoonHub](https://github.com/BaekjoonHub/BaekjoonHub). - gajicoding/coding_test

github.com


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

 

코딩테스트 연습 | 프로그래머스 스쿨

개발자 취업의 필수 관문 코딩테스트를 철저하게 연습하고 대비할 수 있는 문제를 총망라! 프로그래머스에서 선발한 문제로 유형을 파악하고 실력을 업그레이드해 보세요!

school.programmers.co.kr