일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 정수 삼각형
- mermaid js
- 18111
- Hasing
- 이분탐색
- 깊이 우선 탐색
- 1620
- 다이내믹 프로그래밍
- 5525
- 숫자 문자열과 영단어
- 10162
- 주식 가격
- BOJ
- Git Convention
- 소수 체크
- js
- n^2 배열 자르기
- javascript
- 구간 합 구하기 4
- codeSyntaxHighlight
- 프로그래머스
- react
- 2018 KAKAO BLIND RECRUITMENT
- 위클리 챌린지
- 없는 숫자 더하기
- 4796
- C++
- 브루트포스 알고리즘
- colorSyntax
- 옵셔널 체이닝 연산자
Archives
- Today
- Total
개발하는 kim-hasa
[c++][프로그래머스] 이진 변환 반복하기 본문
https://programmers.co.kr/learn/courses/30/lessons/70129
코딩테스트 연습 - 이진 변환 반복하기
programmers.co.kr
특정 2진수에서 0을 제거하고 1의 개수를 2진수로 변환해서 1이 될 때까지 반복하는 문제입니다.
2진수의 1의 개수를 카운트하고 0의 개수를 더해줍니다. 1의 개수가 1개라면 반복문을 빠져나오고, 그렇지 않다면
다시 2진수로 변경해서 계산합니다.
#include <string>
#include <vector>
#include <stack>
using namespace std;
vector<int> solution(string s) {
vector<int> answer;
int count = 0;
int zerocount = 0;
string str = s;
while(true)
{
int onecount = 0;
int zero = 0;
stack<char> s1;
for(int i=0; i<str.length(); i++)
{
if(str[i] == '1')
{
onecount++; // 1의 개수
}
}
zero = str.length() - onecount; // 제거한 0의 개수
zerocount += zero;
count++;
if(onecount == 1) // 1이 한개라면 종료
{
answer.push_back(count);
answer.push_back(zerocount);
break;
}
int div;
string str2 = "";
while(onecount > 0) // onecount를 2진수 문자열로 변환
{
div = onecount % 2;
if(div == 1)
{
s1.push('1');
}
else
{
s1.push('0');
}
onecount = onecount / 2;
}
while(!s1.empty())
{
str2 += s1.top();
s1.pop();
}
str = str2;
}
return answer;
}
'Algorithm > Programmers(c++)' 카테고리의 다른 글
[c++][프로그래머스] n^2 배열 자르기 (0) | 2022.03.03 |
---|---|
[c++][프로그래머스] 더 맵게 (0) | 2022.03.03 |
[c++][프로그래머스] 없는 숫자 더하기 (0) | 2021.09.28 |
[c++][프로그래머스] 위클리 챌린지 8주차 (0) | 2021.09.27 |
[c++][프로그래머스] 최고의 집합 (0) | 2021.09.24 |