Programmers/Level 2
C++ / 프로그래머스 / 이진 변환 반복하기
GitHubSeob
2023. 6. 26. 23:07
문제
https://school.programmers.co.kr/learn/courses/30/lessons/70129
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제풀이
erase함수를 통해 0을 모두 지우고 지운 개수를 카운트한다.
변환 횟수를 +1, 카운트한 0의 개수를 answer에 저장한다.
이진수로 변환하는 stob 함수를 만들어 s를 이진수로 변환한다.
s가 1로 변할때 까지 반복한다.
다 풀고 나서 다른 분의 풀이를 봤는데 굳이 이진수로 변환할때 reverse를 할 필요가 없었다는걸 깨달았다.
코드
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string stob(int num) {
string binary("");
while (num > 0) {
binary += to_string(num % 2);
num /= 2;
}
reverse(binary.begin(), binary.end());
return binary;
}
vector<int> solution(string s) {
int idx(0), zero(0);
vector<int> answer(2, 0);
while (s != "1") {
while (s.find('0') != -1) {
s.erase(find(s.begin(), s.end(), '0'));
zero++;
}
answer[0]++;
answer[1] += zero;
s = stob(s.size());
zero = 0;
}
return answer;
}