問題描述:
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.
譯文:
你的任務是寫出這樣一個函式:它可以接收任何非負整數,并以降序回傳其數字,本質上講,請重新排列數字以創建可能的最大數字,
總體思想:就是先給它轉換成string,然后再排序(按從大到小)
我的答案:
function descendingOrder(n){
let arr = n.toString();
let arr0 = new Array();
for(let i=0; i<arr.length; i++){
arr0.push(Number(arr[i]));
}
arr0.sort(function(a, b){
return a - b;
})
n = 0;
for(let i=0; i<arr0.length; i++){
n += arr0[i] * Math.pow(10, i);
}
return n;
}
Best Answer: solutions下排在最前面的答案:
function descendingOrder(n){
return parseInt(String(n).split('').sort().reverse().join(''))
}
只是對比一下,沒有對比,就沒有傷害,寫完博客的我,表示已受到一萬點傷害,希望自己可以化悲傷為動力😜
對上面Best Answer的解讀:
我們就找一組簡單的資料測驗一下:4253617
n = 4253617;
n = String(n);
console.log(n); //4253617
//此時,typeof n == string
n = n.split('');
console.log(n); //["4", "2", "5", "3", "6", "1", "7"]
n.sort(); //注意,使用n.sort()可以直接改變n的值
console.log(n); //["1", "2", "3", "4", "5", "6", "7"]
n.reverse(); //n.reverse()也可以直接改變n的值
console.log(n); //["7", "6", "5", "4", "3", "2", "1"]
n = n.join('');
console.log(n); //7654321
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/240870.html
標籤:區塊鏈
下一篇:2020-12-25
