프로그래머스 알고리즘/2단계
(프로그래머스 c++)다음 큰 숫자
naeunchan
2020. 5. 25. 14:31
728x90
반응형
bitset을 이용하여 문제를 풀었다..!
bitset은 int형 n을 bit 형태로 만들어 주기 때문에 이 문제에 적용하기 좋다..!
우선 1의 개수를 알아야 하기 때문에 count 변수에 n의 1의 개수를 넣어준다.
그리고 answer에는 n + 1을 넣어주고, n + 1을 bit로 바꾸었을 때 1의 개수가 count와 같은 것이
나올 때까지 answer++을 해주면 쉽게 구할 수 있다.
#include <string>
#include <vector>
#include <bitset>
using namespace std;
int solution(int n) {
int answer = n + 1;
int count = bitset<20>(n).count();
while(bitset<20>(answer).count() != count)
answer++;
return answer;
}
728x90
반응형