1. 문제
코딩테스트 연습 - 다음 큰 숫자
자연수 n이 주어졌을 때, n의 다음 큰 숫자는 다음과 같이 정의 합니다. 조건 1. n의 다음 큰 숫자는 n보다 큰 자연수 입니다. 조건 2. n의 다음 큰 숫자와 n은 2진수로 변환했을 때 1의 갯수가 같습니
programmers.co.kr
2. 소스코드
- bitset을 쓰면 정말 간단히 풀리는 문제.
- &연산을 이용하는 방법도 있다. 좀 더 깊게 공부하고 싶으면 &연산자와 쉬프트 연산을 해보는 게 좋을 것 같다.
소스코드 - bitset
#include <string>
#include <vector>
#include <bitset>
using namespace std;
int solution(int n) {
int num = bitset<20>(n).count();
int next = n + 1;
while(bitset<20>(next).count() != num)
next++;
return next;
}
소스코드 - &연산
#include <string>
using namespace std;
int getCnt1(int number){
int cnt = 0;
for(int i = 0 ; i < 31; ++i){
if(number & (1 << i))
cnt++;
}
return cnt;
}
int solution(int n) {
int cnt = getCnt1(n);
int next = n + 1;
while(true){
if(cnt == getCnt1(next))
return next;
next++;
}
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[ 프로그래머스 / Map ] 영어 끝말잇기 (0) | 2020.07.01 |
---|---|
[ 프로그래머스 / 문자열 ] 오픈채팅방 (0) | 2020.07.01 |
[ 프로그래머스 / 우선순위큐 ] 라면공장 (0) | 2020.06.30 |
[ 프로그래머스 / 완전탐색 ] 카펫 (0) | 2020.06.30 |
[ 프로그래머스 / Map ] 위장 (0) | 2020.06.30 |