algorithm
[프로그래머스] 이진 변환 반복하기
지제로
2022. 9. 14. 20:30
풀이 단계
1. s가 1이 될 때까지 반복한다.
2. s에서 현재 0의 개수(tmp_zero)를 구한다.
3. 0을 제외한 길이(tmp)를 구한다.
4. 해당 수를 이진변환해준다.
5. 변환한 횟수, 변환 과정에서 제거된 모든 0의 개수를 더한다.
#include <string>
#include <vector>
using namespace std;
string to_binary(int num) {
string s = "";
while (num != 0) {
s += num % 2 == 0 ? '0' : '1';
num /= 2;
}
return s;
}
vector<int> solution(string s) {
vector<int> answer;
int zero_count = 0, change_count = 0, tmp, tmp_zero = 0;
//printf("%d \n",stoi(s));
while (s != "1") {
tmp = 0, tmp_zero = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '0')
tmp_zero++;
}
tmp = s.length() - tmp_zero; //0제거 후 길이
s = to_binary(tmp); //이진 변환 결과
zero_count += tmp_zero;
change_count++;
}
answer.push_back(change_count);
answer.push_back(zero_count);
return answer;
}