
이 문제는 주어진 수에서 2진수로 변환하였을때 1의 개수가 똑같은 수 중 큰 수를 구하는 문제다. 그렇다면 어떻게 cpp로 푸는지 알아보자면. cpp에는 bitset이라는 쉽게 이진수로 변환할 수 있는 자료형이 있다. 이 것을 이용하면, 이진수에 1이 몇개있는지 확인이 가능하다. bitset알아보기
그렇다면 이제 한번 제작을 해보자면..
- 우선 n의 값을 이진수로 변환
- 변환한 n값과 n+i의값을 검사
- n+i값과 n값의 이진수의 1개수를 확인
- 만약 다르다면 2번으로 넘기기
- 만약 같다면 return
#include<iostream>
#include<string>
#include <vector>
#include <algorithm>
#include <bitset>
using namespace std;
string a;
bool check(bitset<32> b, int s) {
//32자리의 이진수로 변환
bitset<32> m(s);
// 1의 개수 비교
if (b.count() == m.count()) {
return true;
}
else {
return false;
}
}
int solution(int n) {
int answer = 0;
answer = n+1;
//32자리의 이진수로 변환
bitset<32> my_b(n);
while (!check(my_b, answer)) {
answer++;
}
return answer;
}