Programmers/Level 2

C++ / 프로그래머스 / 다음 큰 숫자

GitHubSeob 2023. 6. 29. 22:52

문제

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

 

프로그래머스

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

programmers.co.kr

문제풀이

1. 십진수 n을 이진수로 변환 (큰 숫자를 구할 때 자릿수 증가를 대비하여 끝에 0을 붙임)

2. next_permutation을 통해 한 번만 다음 큰 숫자로 변환

3. 이진수 n을 십진수로 변환

 

코드

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

int solution(int n) {
	int idx(0), btoi(1), answer(0);
	vector<int>num;
    
	while (n > 0) {
		num.push_back(n % 2);
		n /= 2;
	}
	num.push_back(0);
	reverse(num.begin(), num.end());

	next_permutation(num.begin(), num.end());

	for (idx = num.size()-1; idx >= 0; --idx) {		
		answer += (num[idx] * btoi);
		btoi *= 2;
	}
    return answer;
}