본문 바로가기

코딩 테스트/프로그래머스

[프로그래머스 Level 2, C++] 다음 큰 숫자

728x90
반응형

문제 : 다음 큰 숫자


풀이 방법

2진수로 변환만 한다면 간단한 문제인데 bitset의 count 메소드를 알았다면 좋았을 것 같다 bitset의 count메소드는 1의 개수를 반환해주는데 이 문제는 1의 개수가 같아야 한다는 조건이 있으니 더 쉽게 접근 할 수 있었을 것 같다.


소스 코드

#include <string>
#include <vector>
#include <algorithm>
using namespace std;

string toBinary(int n)
{
    string r;
    while (n != 0){
        r += ( n % 2 == 0 ? "0" : "1" );
        n /= 2;
    }
    return r;
}

int solution(int n) {			
    int answer = 0;
    string bin = toBinary(n);
    int count_1 = count(bin.begin(), bin.end(), '1');
    while(true) {
        answer = ++n;
        bin = toBinary(answer);
        if(count_1 == count(bin.begin(), bin.end(), '1')) break;
    }
    return answer;
}

 

728x90
반응형