study
이진변환 반복하기[프로그래머스]
Date: 2026-01-18 22:59
Update: 2026-01-20 07:58
[프로그래머스] 이진변환 반복하기
접근:
- 문자열 x 에 대한 0을 지워서 y를 리턴 합니다. (전역변수를 이용해 사라진 0의 개수를 카운트)
- y의 길이를 토대로 2진수로 변환합니다. (전역변수를 이용해 함수의 호출 횟수를 카운트)
- 최종 문자열의 길이가 1일 될 때 까지 반복합니다.
- 카운트한 횟수를 결과 값에 입력합니다.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int count_convert = 0;
int count_remove_zero = 0;
string removeZero(string s)
{
string res = "";
for(auto c : s)
{
if(c != '0') res += c;
else count_remove_zero++;
}
return res;
}
string lengthToBinary(string s)
{
count_convert++;
int x = s.size();
string res = "";
while(x > 0)
{
res += to_string(x % 2);
x /= 2;
}
reverse(res.begin(), res.end());
return res;
}
vector<int> solution(string s) {
vector<int> answer;
string temp = s;
while(temp.size() != 1)
{
temp = removeZero(temp);
temp = lengthToBinary(temp);
}
answer.push_back(count_convert);
answer.push_back(count_remove_zero);
return answer;
}
.gif)