Algorithm/프로그래머스

[프로그래머스] 다음 큰 숫자 with C++

nowkoes 2023. 6. 2. 00:00

문제 설명


제한 사항 및 입출력 예제


개념

 주어진 정수 n의 이진 표현에서 1의 개수가 같은 n보다 큰 정수 중 가장 작은 정수를 찾는 문제다. 이진 표현을 하기 위해 bitset 라이브러리를 이용하면 효율적으로 문제를 해결할 수 있다.


풀이

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

int CountOnesInBinary(int number)
{
    bitset<32> binaryRepresentation(number);
    string binaryString = binaryRepresentation.to_string();

    return count(binaryString.begin(), binaryString.end(), '1');
}

int solution(int n) 
{
    int numberOfOnes = CountOnesInBinary(n);
    int nextNumber = n;
    
    while (true)
    {
        nextNumber++;
        int onesInNextNumber = CountOnesInBinary(nextNumber);

        if (numberOfOnes == onesInNextNumber)
            return nextNumber;
    }
}

 bitset을 이용해 이진 변환을 한 후 1의 개수를 출력하기 위해 CountOnesInBinary() 함수를 작성하였다.

반응형