Level 2. 다음 큰 숫자
앞에 비트를 추가하며 이진수로 변환하기 때문에 deque를 사용했다.
비트 배열에 next_permutation() 함수를 적용하면 정확히 이 문제의 정답을 찾을 수 있다.
#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;
int solution(int n)
{
int answer = 0;
deque<int> binary;
do binary.emplace_front(n & 1);
while (n >>= 1);
binary.emplace_front(0);
next_permutation(binary.begin(), binary.end());
for (int bit : binary)
(answer <<= 1) += bit;
return answer;
}
bitset을 활용하면 간단하게 해결할 수 있었다.
n + 1부터 1씩 증가시키며, 1의 개수가 n과 같은 가장 작은 수를 찾는다.
#include <iostream>
#include <bitset>
using namespace std;
int solution(int n)
{
int cnt = bitset<20>(n).count();
while (bitset<20>(++n).count() != cnt);
return n;
}
'자료구조 & 알고리즘 > 프로그래머스' 카테고리의 다른 글
Level 2. 최솟값 만들기 (0) | 2023.04.04 |
---|---|
Level 2. 큰 수 만들기 (0) | 2023.04.03 |
Level 2. 숫자의 표현 (0) | 2023.04.01 |
Level 2. 프린터 (0) | 2023.03.31 |
Level 2. 올바른 괄호 (0) | 2023.03.30 |