관리 메뉴

DuckingRacoon

프로그래머스 | 이진 변환 반복하기 본문

알고리즘

프로그래머스 | 이진 변환 반복하기

따킹라쿤

출처

🌐 코딩테스트 연습 - 이진 변환 반복하기 | 프로그래머스 스쿨

문제

문제 설명

0과 1로 이루어진 어떤 문자열 x에 대한 이진 변환을 다음과 같이 정의합니다.

  1. x의 모든 0을 제거합니다.
  2. x의 길이를 c라고 하면, x를 "c를 2진법으로 표현한 문자열"로 바꿉니다.

예를 들어, x = "0111010"이라면, x에 이진 변환을 가하면 x = "0111010" -> "1111" -> "100" 이 됩니다.

0과 1로 이루어진 문자열 s가 매개변수로 주어집니다. s가 "1"이 될 때까지 계속해서 s에 이진 변환을 가했을 때, 이진 변환의 횟수와 변환 과정에서 제거된 모든 0의 개수를 각각 배열에 담아 return 하도록 solution 함수를 완성해주세요.

 

제한사항

  • s의 길이는 1 이상 150,000 이하입니다.
  • s에는 '1'이 최소 하나 이상 포함되어 있습니다. 

입출력 예시

s result

"110010101001" [3,8]
"01110" [3,3]
"1111111" [4,1]

풀이

1차 풀이

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> solution(string s) 
{
    int convCount = 0, deleteCount = 0;

    while (s != "1")
    {
        int ones = 0, zeros = 0;
        for (const char& c : s)
        {
            if (c == '1') ++ones;
            else ++zeros;
        }

        deleteCount += zeros;
        ++convCount;

        s.clear();
        while (ones != 0)
        {
            if (ones % 2 == 0) s.push_back('0');
            else s.push_back('1');

            ones /= 2;
        }

        reverse(s.begin(), s.end());
    }

    return { convCount, deleteCount };
}

2차 풀이

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> solution(string s) 
{
    int convertCount = 0, deleteCount = 0;

    while (s != "1")
    {
        ++convertCount;

        int ones = 0;
        for (const char& c : s)
        {
            (c == '1') ? ++ones : ++deleteCount;
        }

        s.clear();

        while (ones != 0)
        {
            (ones % 2) ? s.push_back('1') : s.push_back('0');
            ones /= 2;
        }

        reverse(s.begin(), s.end());
    }

    return { convertCount, deleteCount };
}

Review

1️⃣ 2차 풀이는 너무 호들갑일까?

2️⃣while문 안에 while문… 불편하다