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

well-life-gm·2021년 11월 3일
0

프로그래머스

목록 보기
20/125

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

  1. 주어진 문자열에서 0의 갯수를 센다.
  2. 문자열 길이에서 0의 갯수를 빼면 0을 제외한 문자열의 길이가 된다.
  3. 이를 2진법으로 변환한다.
  4. 3의 결과가 "1"이 아니라면 1단계부터 다시 반복한다.

다른 분들도 위 방법과 비슷하게 푼듯.

#include <string>
#include <vector>

using namespace std;

void to_binary(int num, string &s) 
{
    string tmp = "";
    while(1) {
        tmp.insert(0, to_string(num % 2));
        num = num / 2;
        if(num == 0)
            break;
    }
    s = tmp;
}

vector<int> solution(string s) {
    vector<int> answer;
    int iter = 0, total = 0;
    while(1) {
        int size = s.size();
        int zero_cnt = 0;
        for(int i=0;i<size;i++) {
            if(s[i] != '0')
                continue;
            zero_cnt++;
        }
        total += zero_cnt;
        iter++;
        to_binary(size - zero_cnt, s);
        if(s.compare("1") == 0)
            break;
    }
    answer.push_back(iter);
    answer.push_back(total);
    return answer;
}

결과

profile
내가 보려고 만든 블로그

0개의 댓글