Free Lines Arrow
본문 바로가기
Algorithm/프로그래머스 알고리즘

[프로그래머스] 이진변환 반복

by skahn1215 2021. 6. 14.
728x90
반응형

문제

분석

따로 크게 분석할게 없었다.

단 중요한건 제목부터 이진변환 반복이라는것.

즉 나는 2진변환로직 구현 -> 재귀로 반복 해주었다.

재귀로 계속 반복하다가 더이상 변환할게 없을때 중단 하였다.

 

 

 

 

구현

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

void solve(int size, int &delCnt, int &cnvCnt );

vector<int> solution(string s) {
    vector<int> answer;
    
    vector<int> binVector;
    int delCnt = 0;
    int cnvCnt = 1;
    
    for(int i = 0 ; i < s.size(); i++){
        if( s.at(i) == '0'){
            delCnt++;
        } else {
            binVector.push_back(1);
        }
    }
    solve(binVector.size(), delCnt, cnvCnt);
    answer.push_back(cnvCnt);
    answer.push_back(delCnt);
    return answer;
}

void solve(int size, int &delCnt, int &cnvCnt)
{
    if(size == 1){
        return;
    }
    
    int nmg = 0;
    int val = size;
    int binaryCnt = 0;
    while(val != 0){
        nmg = val%2;
        val = val/2;
        if(nmg == 1){
            binaryCnt++;
        } else {
            delCnt++;
        }
    }
    
    cnvCnt++;
    solve(binaryCnt,delCnt,cnvCnt);
}

 

 

 

 

결과

 

 

 

 

문제링크:https://programmers.co.kr/learn/courses/30/lessons/70129

 

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

 

programmers.co.kr

 

728x90
반응형

댓글