https://github.com/GyungSikHan/AlgorithmTest/tree/main/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4/2/70129.%E2%80%85%EC%9D%B4%EC%A7%84%E2%80%85%EB%B3%80%ED%99%98%E2%80%85%EB%B0%98%EB%B3%B5%ED%95%98%EA%B8%B0
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int zero{};
int Count{};
vector<int> solution(string s)
{
vector<int> answer;
string temp{};
for (int i = 0; i < s.size(); i++)
{
if (s[i] == '0')
zero++;
else
temp += s[i];
}
if(s == "1")
{
answer.push_back(Count);
answer.push_back(zero);
return answer;
}
Count++;
int length = temp.size();
string i{};
while (length > 0)
{
i += to_string(length%2);
length /= 2;
}
reverse(i.begin(), i.end());
answer = solution(i);
return answer;
}
- 더 쉽게 푸는 방법도 있을지 모르지만 재귀함수를 사용하여 풀었다
- 일단 문자열 s에서 0을 제거한 뒤, 이진 변환을 통해 이진수를 구했다
- 이때 0을 제거할땐 0을 제거한 만큼 수를 count해주고, 이진 변환이 끝이난 뒤 변환 횟수를 count해주었다
- 0을 제거하고 이진변환을 하기 전 문자열 s가 1이 됐다면 answer에 현재 0을 제거한 횟수와 이진변환 횟수를 저장해준 뒤 answer를 리턴해주어 재귀함수를 종료해준다
- 이진변환이 끝났다면 우리가 원하는 이진 변환과 역순으로 문자열에 저장이 되어있을 것인데, algorithm.h안에 reverse 함수를 이용해 문자열을 뒤집어주고 재귀함수를 들어갈 것이다
- 이를통해 리턴되는 값을 answer에 저장해주면 0을 지운 수와 이진변환을 한 횟수를 저장한 answer를 리턴할 수 있다