Descending Order
Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
Examples :
Input:42145
Output:54421
Input:145263
Output:654321
Input:123456789
Output:987654321
📌 Needs ) 숫자를 내림차순으로 정렬하라.
📁 Sol )
1. String(n) : n을 문자열로 변환
2. split('') : ''으로 문자열 구분
3. sort() : 배열 정렬 (오름차순)
4. reverse() : 배열 반대로 정렬 (내림차순)
5. join('') : 요소들끼리 연결
6. parseInt : 정수 반환
function descendingOrder(n){
return parseInt(String(n).split('').sort().reverse().join(''));
}
💡 Other ways to solve )
.sort()
: 사전식 정렬
.sort((a, b) => b - a)
: 내림차순
.sort((a, b) => a - b)
: 오름차순
.toString() 이나 (n + '') 과 같이 빈 문자열을 더해주는 것도 문자로 만들 수 있는 방법이다.
function descendingOrder(n){
return Number(n.toString().split('').sort((a,b)=> b-a).join(''));
}