C++/programmers 코딩테스트(level 2) C++

[C/C++] programmers Level 2 이진 변환 반복하기

CE : 하랑 2023. 10. 11. 14:53

 

 

 

 

코드

 

#include <string>
#include <vector>

using namespace std;

vector<int> solution(string s) {
    vector<int> answer(2,0); // 0~1 범위의 값을 0으로 채움
    
    while(s!="1"){ // s가 "1"일 시 반복문 탈출
        string check1=""; // 0 제거 후 1만 저장
        
        answer[0]++; // 이진 변환 횟수 카운트
        
        for(int i=0;i<s.size();i++){
            if(s[i]=='0'){
                answer[1]++; // 0의 개수 카운트
            }else{
                check1=check1+"1";
            }
        }
        
        int size1=check1.size();
        s=""; // s 값 초기화
        
        while(size1){ // 10진법 -> 2진법으로 변환
            s=s+to_string(size1%2);
            size1=size1/2;
        }
    }
    
    return answer;
}