How to Sort an Integer and Reverse it: Python vs JavaScript.

Olivia
2 min readJun 4, 2021

Beginner friendly: Sorting a string and then reversing it to return the highest possible int.

If we had the integer 1105198, we would want to sort it to 0111589, then reverse it in order to make the highest integer possible, which would be 9851110.

In JavaScript

  • Define your function with a parameter for the integer
  • Cast the integer into a String data-type and split the string on each character
  • On the string, chain the sort method and the reverse method
  • To change the string back to an integer, use the Number() object. Inside use the join method to bring each individual character back together without spaces
  • return your final result!

function reverseNum(num) {

const numToString = String(num).split(“”);

numToString.sort().reverse();

const backToNum = Number(numToString.join(“”));

return backToNum;

}

A condensed version would look like this:

function reverseNum2(num) {

result = String(num).split(“”).sort().reverse().join(“”);

return result;

}

Short code isn’t always ‘best code’. What’s best is that you understand what’s happening line by line.

Don’t forget to call your function with the argument (the integer) you want to sort and reverse.

In Python

  • Define your function with the parameter for the integer
  • Assigned to a variable, cast the parameter into a String
  • Assigned to a variable, take the above variable and run the sorted method
  • Assigned to a variable, take the above variable and reverse it using [::-1]
  • Join the above variable together using the join method
  • Print your result!

def reverse_number(num):

num1 = str(num)

num2 = sorted(num1)

reverse_num2 = num2[::-1]

joined_nums = int(“”.join(reverse_num2))

print(joined_nums)

Don’t forget to call your function with the argument (the integer) you want to sort and reverse.

Happy coding!

--

--

Olivia

From Law Graduate to Fullstack Developer / Professional Googler. Join me as I blog about the highs & lows of learning to code and navigating my new career path