在 JavaScript 中返回數字並按降序排列數字


問題

我們需要編寫一個 JavaScript 函式,它獲取數字 n。我們的函式應以降序返回其數字。實質上,我們應該重新排列數字以建立最大可能的數字。

範例

以下是程式碼 −

 即時演示

const num = 5423267;
const arrangeInDescending = (num = 1) => {
   const str = String(num);
   const arr = str.split('');
   arr.sort((a, b) => {
      return +b - +a;
   });
   const newStr = arr.join('');
   const res = Number(newStr);
   return res;
};
console.log(arrangeInDescending(num));

輸出

以下是控制檯輸出 −

7654322

於: 17-Apr-2021 更新

154 次檢視

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.