Level 2. 이진 변환 반복하기
![](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
문제에 나와 있는 대로만 따라가면 잘 풀 수 있는 문제다.
remove() 함수가 지워주기까지 하는 것이 아니라, 삭제할 원소들을 뒤로 몰아넣을 뿐이라는 걸 깜빡한 것만 빼면 크게 어려운 건 없었다.
십진수를 이진수로 변환할 떄는 LSB 비트 마스킹과 Shift Right 비트 연산자를 사용했다.
<cpp />
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
string ToBinaryString(int num)
{
string s = "";
if (num == 0)
return "0";
do
s = (num & 1 ? "1" : "0") + s;
while (num >>= 1);
return s;
}
vector<int> solution(string s)
{
vector<int> answer(2, 0);
size_t o_length = s.length();
while (s != "1")
{
s.erase(remove(s.begin(), s.end(), '0'), s.end());
answer[1] += (o_length - s.length());
s = ToBinaryString(s.length());
o_length = s.length();
++answer[0];
}
return answer;
}
'자료구조 & 알고리즘 > 프로그래머스' 카테고리의 다른 글
Level 2. 튜플 (0) | 2023.03.21 |
---|---|
Level 2. 오픈채팅방 (0) | 2023.03.20 |
Level 2. 최댓값과 최솟값 (0) | 2023.03.18 |
Level 2. 피로도 (0) | 2023.03.17 |
Level 2. 뒤에 있는 큰 수 찾기 (0) | 2023.03.16 |