Post

[Programmers] #181880 - 1로 만들기 [Java][C++][Python]

[Programmers] #181880 - 1로 만들기 [Java][C++][Python]

문제 링크


1. 아이디어

각 원소 $x$에 대해 짝수는 반으로 나누고 홀수는 1을 뺀 뒤 반으로 나누는 두 규칙은 모두 $\lfloor x / 2 \rfloor$ 하나로 합쳐지므로 짝수·홀수를 가를 필요가 없다. 각 원소를 1이 될 때까지 이 연산으로 줄이며 센 횟수를 모든 원소에 대해 더하면 답이다. $\lfloor x / 2 \rfloor$은 이진 표기에서 끝 한 자리를 떼는 연산이라 원소 하나의 횟수는 $\lfloor \log_2 x \rfloor$이지만, 원소가 30 이하라 직접 세어도 충분하다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
    public int solution(int[] num_list) {
        int cnt = 0;
        for (int x : num_list) {
            while (x > 1) {
                x /= 2;
                cnt++;
            }
        }

        return cnt;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <bits/stdc++.h>
using namespace std;

int solution(vector<int> num_list) {
    int cnt = 0;
    for (int x : num_list) {
        while (x > 1) {
            x /= 2;
            cnt++;
        }
    }

    return cnt;
}
1
2
3
4
5
6
7
8
def solution(num_list):
    cnt = 0
    for x in num_list:
        while x > 1:
            x //= 2
            cnt += 1

    return cnt

This post is licensed under CC BY 4.0 by the author.