본문 바로가기
코테연습

3.Descending Order

by hxunz 2022. 3. 10.

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

 

function descendingOrder(n){
  n = n.toString();
  const num = n.split('');
  const result = num.sort(function (a, b) {
      return b - a;
    });
    const answer = result.join('');
    const ans = parseInt(answer);
    return ans;
}

뭔가 엥 됐네?! 하면서 완성된 코드,,,ㅋ 

역시 다른 사람들이 한거 보니까 한줄로 깔끔하게 끝냈더라ㅜ ㅋ

function descendingOrder(n){
  return parseInt(String(n).split('').sort().reverse().join(''))
}

이렇게 깔끔하게 하는 방법이 있었구나,,,

 

그래도 이번에는 javascript에서 내림차순 정렬하는 방법을 배웠다

오름 차순으로 하려면 return 값을 a-b로 하면 되더라~

'코테연습' 카테고리의 다른 글

6.Isograms  (0) 2022.03.16
5.You're a square!  (0) 2022.03.14
4.Get the Middle Character  (0) 2022.03.11
2. Disemvowel Trolls  (0) 2022.03.09
1. Square Every Digit  (0) 2022.03.09

댓글