이진 변환 반복하기

magicdrill·2025년 1월 7일
0

이진 변환 반복하기

귀찮은 이진법 변환을 쉽게 하는 라이브러리 함수를 배웠다.
#include <bitset>으로 헤더를 추가하고, bitset<비트수>(변환할 십진수)로 만들 수 있다.
이때 비트수는 int의 경우 32비트지만 넉넉하게 64로 하는게 일반적이다.
이진 변환 결과는 0000....101010 이런식으로 앞에 0이 붙는데 문자열이 아니고 bitset이라는 타입이다. 이를 to_string()같은 함수로 문자열로 바꾸거나 할 수 있다.

#include <string>
#include <vector>
#include <iostream>
#include <bitset> //이진수 변환 라이브러리 함수

using namespace std;

vector<int> solution(string s) {
    vector<int> answer;
    int i, count, zero_count = 0, transform_count = 0;
    
    while(s != "1")
    {
        count = 0;
        for(i = 0; i < s.length(); i++){
            if(s[i] == '1'){
                count++;
            }
            else{
                zero_count++;
            }
        }
        
        s = bitset<64>(count).to_string();
        transform_count++;
        s = s.substr(s.find('1'));//쓸모없는 0 지우기
        cout << "이진수 변환 후 : " << s << "\n";   
    }
    answer.push_back(transform_count);
    answer.push_back(zero_count);
    
    return answer;
}

0개의 댓글