https://school.programmers.co.kr/learn/courses/30/lessons/12911

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

[C++][프로그래머스][Lv2] 12911. 다음 큰 숫자 

 


❗주의할 점 

: 10진수를 2진수로 바꾸는 방법을 알아야 풀 수 있는 문제였다.

: 얼마전에 비슷한 문제를 풀어서 푸는데 어려움은 없었다. 그리고 문제를 꼼꼼히 읽어야겠다는 생각을 했다....

 

사용한 함수

https://youcheachae.tistory.com/11

 

[C++][프로그래머스][Lv2] 70129. 이진 변환 반복하기

https://school.programmers.co.kr/learn/courses/30/lessons/70129 프로그래머스코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는

youcheachae.tistory.com

 


✅풀이방법 

#include <string>
#include <bitset>

using namespace std;

int solution(int _num) 
{
    int _idx = 1;
    int _answer = 0;

    // 기준이 되는 1의 갯수 
    int standartOneCnt = 0;
    // 2진수를 10진수로 변환 후, 문자열로 변환
    string numBinary = bitset<32>(_num).to_string();
    // 1로 시작하는 부분부터 끝까지 자르기
    string subNumBinary = numBinary.substr(numBinary.find('1'));

	// 기준이 되는 1의 갯수 구하기
    // algorithm 헤더의 count를 사용했으면 더 간편하게 가능함 
    for (int i = 0; i < subNumBinary.size(); i++)
    {
        if (subNumBinary[i] == '1')
            standartOneCnt++;
    }

    while (true)
    {
 	// 다음수 구하기 
        int _next = _num + _idx;

 	// 2진수 변환 후 1로 시작하는 부분~끝까지 자르기
        string _binary = bitset<32>(_next).to_string();
        string _subBinary = _binary.substr( _binary.find('1'));

	// 다음수의 1 구하기 
        int nextOneCount = 0;
        for (int i = 0; i < _subBinary.size(); i++)
        {
            if (_subBinary[i] == '1')
                nextOneCount++;	
        }

	// 문제조건 n과 n다음수를 2진수로 변환했을 때 1갯수가 같으면
        if (standartOneCnt == nextOneCount)
        {
            _answer = _next;
            break;
        }
        
        _idx++;
    }

    return _answer;
}

 


https://github.com/kimYouChae/C-Programmers

 

GitHub - kimYouChae/C-Programmers

Contribute to kimYouChae/C-Programmers development by creating an account on GitHub.

github.com

 

+ Recent posts