LV1_정수 내림차순으로 배치하기(C++)

sonyrainy·2022년 7월 23일
0

프로그래머스_LV1

목록 보기
10/39

🚗문제 설명

함수 solution은 정수 n을 매개변수로 입력받습니다. n의 각 자릿수를 큰것부터 작은 순으로 정렬한 새로운 정수를 리턴해주세요. 예를들어 n이 118372면 873211을 리턴하면 됩니다.

🚓제한 조건

n은 1이상 8000000000 이하인 자연수입니다.

🚕입출력 예시

🚐코드_1

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

long long solution(long long n) {
    long long answer = 0;
    int sum = 0;
    vector <int> arr;
    
    while(n!=0){
        int k = 0;
        k = n % 10;
        n = n / 10;
        arr.push_back(k);
    }
    
    sort(arr.begin(), arr.end(), greater<>());
    
    for(int i = 0;i<arr.size();i++){
        answer = answer*10 + arr[i];
    }
    
    
    return answer;
}

🚐코드_2(string, stoll 이용)

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

long long solution(long long n) {
	string answer = to_string(n);
	sort(answer.begin(), answer.end(), greater<>());
	return stoll(answer);
}


내림차순 정렬 : sort(ans1.begin(), ans1.end(), greater<>());
stoll : string to long long, string을 long long형으로 형변환한다.
stoi : string to integer, string을 int형으로 형변환한다.
to_string : int, double, long long형 등을 string형으로 형변환한다.

profile
@sonyrainy

0개의 댓글