https://school.programmers.co.kr/learn/courses/30/lessons/70129
반복문을 이용한 0 제거, 0을 제거한 문자열의 길이를 이진수로 변환 하면서 0제거 카운트, 해당 과정 횟수도 카운트
#include <string>
#include <vector>
using namespace std;
string tobinary(string s)
{
int num = s.length();
string r = "";
while ( num != 0 )
{
r += ( num % 2 == 0 ? "0" : "1" );
num /= 2;
}
return r;
}
vector<int> solution(string s) {
vector<int> answer;
int zero = 0;
int times = 0;
while(s.length() != 1)
{
for(int i = 0; i < s.length(); i++)
{
if(s[i] == '0')
{
s.erase(s.begin() + i);
i--;
zero++;
}
}
s = tobinary(s);
times++;
}
answer.push_back(times);
answer.push_back(zero);
return answer;
}
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(string s) {
int zeros{0}, num_transform{0}; vector<bool> bin;
for_each(s.cbegin(),s.cend(),[&bin](const char c){bin.emplace_back(c=='1');}); //s를 이진수로 변환
while(true){
if(bin==vector<bool>{true}) break;
int ones = count(bin.cbegin(),bin.cend(),true); //1갯수를 셈
zeros += bin.size()-ones; //0갯수를 셈
bin.clear();
while(ones>0){ bin.emplace_back(ones%2); ones/=2; }//1갯수를 2진수로 바꿈. 순서는 거꾸로지만 계산에는 영향없음
++num_transform; //이진변환 횟수 기록
}
return {num_transform,zeros};
}
일단 string을 vector<bool>에 이진수로 변환해서 넣어준다.
그다음 반복문을 하는데
break 조건문은 vector<bool> {true} 즉 이진수가 1일 때 이다.
1의 갯수를 구하고
1의 갯수를 기반으로 0의 갯수를 구해서 zeros에 취합한다.
bin 벡터를 비우고 1의 갯수를 이진수로 변환하여 bin에 넣어주고 변환 횟수를 ++ 한다.