알고리즘/프로그래머스
Programers 이진 변환 반복하기
내이름은 킹햄찌
2022. 9. 11. 22:25
https://school.programmers.co.kr/learn/courses/30/lessons/70129
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
프로그래머스 이진 변환 반복하기 문제입니다.
아이디어
단순 구현문제입니다. 비트연산자를 많이 쓰려고 노력했습니다.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string convertBinary(int n) {
string temp = "";
while (n != 0) {
temp.append(to_string((int)n & 1));
n = n >> 1;
}
reverse(temp.begin(), temp.end());
return temp;
}
vector<int> solution(string s) {
vector<int> answer;
int zeroCnt = 0;
int convertCnt = 0;
string convertResult = "";
while (convertResult != "1") {
int size = s.size();
convertResult = "";
// 0제거
for (auto&e : s) {
if (e == '1')
convertResult += "1";
}
// 제거된 0 카운트
zeroCnt += size - convertResult.size();
// 2진 변환
convertResult = convertBinary(conve rtResult.size());
s = convertResult;
convertCnt++;
}
answer = { convertCnt, zeroCnt };
return answer;
}