Descending Order || CodeWars Problem and solution in javascript.
- Get link
- X
- Other Apps
Problem: Descending Order
Description: Your task is to make a function that can take
any non-negative integer as a 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
Solution 1#
function descendingOrder(n){
var stringNumber =
n.toString();
var arr =
stringNumber.split('');
var result =
arr.sort(function(a, b){return b - a});
var stringresult =
result.join();
stringresult=
stringresult.replace(/,/g,"");
return
parseInt(stringresult)
}
Solution 2# (slightly more concise)
function descendingOrder(n){
return
parseInt(String(n).split('').sort().reverse().join(''))
}
- Get link
- X
- Other Apps
Comments
Nice Approach. Precisely defined the solution.
ReplyDeleteThanks Oblivia.
Delete