개발하는 kim-hasa

[c++][프로그래머스] 이진 변환 반복하기 본문

Algorithm/Programmers(c++)

[c++][프로그래머스] 이진 변환 반복하기

kim-hasa 2021. 9. 29. 14:23

https://programmers.co.kr/learn/courses/30/lessons/70129

 

코딩테스트 연습 - 이진 변환 반복하기

 

programmers.co.kr

특정 2진수에서 0을 제거하고 1의 개수를 2진수로 변환해서 1이 될 때까지 반복하는 문제입니다.

 

2진수의 1의 개수를 카운트하고 0의 개수를 더해줍니다. 1의 개수가 1개라면 반복문을 빠져나오고, 그렇지 않다면

다시 2진수로 변경해서 계산합니다.

#include <string>
#include <vector>
#include <stack>
using namespace std;

vector<int> solution(string s) {
    vector<int> answer;
    int count = 0;
    int zerocount = 0;
    string str = s;
    
    while(true)
    {
        int onecount = 0;
        int zero = 0;
        stack<char> s1;
        
        for(int i=0; i<str.length(); i++)
        {
            if(str[i] == '1')
            {
                onecount++;     // 1의 개수
            }
        }
        
        zero = str.length() - onecount;     // 제거한 0의 개수
        zerocount += zero; 
        
        count++;
        
        if(onecount == 1)       // 1이 한개라면 종료
        {
            answer.push_back(count);
            answer.push_back(zerocount);
            break;
        }
        
        int div;
        string str2 = "";
        
        while(onecount > 0)         // onecount를 2진수 문자열로 변환 
        {
            div = onecount % 2;
            if(div == 1)
            {
                s1.push('1');
            }
            else
            {
                s1.push('0');
            }
            onecount = onecount / 2;
        }
        
        while(!s1.empty())
        {
            str2 += s1.top();
            s1.pop();
        }
        
        str = str2;
    }
    return answer;
}