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

[코딩 기초 트레이닝] 1로 만들기

by 코딩맛집 2024. 1. 2.

문제 :

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

 

프로그래머스

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

programmers.co.kr

 

해결 :

class Solution {
    public int solution(int[] num_list) {
        int cnt = 0;

        for(int i = 0; i<num_list.length; i++){
            while(num_list[i] != 1){

                if(num_list[i]%2 == 0){
                    num_list[i] = num_list[i]/2;
                }else{
                    num_list[i] = (num_list[i]-1)/2;
                }
                cnt++;
            }
        }

        return cnt;
    }
}

 

다른 사람 풀이:

class Solution {
    public int solution(int[] num_list) {
        int answer = 0;
        for(int i = 0;num_list.length>i;i++){
            while(num_list[i]!=1){
                num_list[i]/=2;
                answer++;
            }
        }
        return answer;
    }
}

int 타입이라 /2만 해줘도 된다.