정수 내림차순으로 배치하기

문제 설명

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

 

제한 사항

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

 

입출력 예

n return
118372 873211

 

Python

def solution(n):
    temp = list(str(n))
    temp.sort(reverse = True)
    return int("".join(temp))

JavaScript

function solution(n) {
    var str = n+"";
    var arr = [];
    for(let i = 0; i < str.length; i++)
        arr.push(Number(str[i]));
    arr.sort((a,b)=>b-a);
    return Number(arr.join(''));
}

C++

Algorithm Function sort

 

functions

Learn more about: functions

docs.microsoft.com

C++ greater Reference

 

greater - C++ Reference

class template std::greater template struct greater; Function object class for greater-than inequality comparison Binary function object class whose call returns whether the its first argument compares greater than the second (as returned by o

www.cplusplus.com

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

using namespace std;

long long solution(long long n) {
   long long answer = 0LL;

    vector<int> temp;

    while(true) {
        temp.push_back(n%10);
        if(n/10==0) break;
        else n = n/10;
    }
    
    sort(temp.begin(), temp.end(), greater<int>());
    
    int i=1;
    while(!temp.empty()) {
        int val = temp.back();
        temp.pop_back();
        answer = answer + val*i;
        i=i*10;
    }

    return answer;
}
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기