-4

How do I sort the digits of a number in order? I want a four digit number to be changed around and made in order from smallest to largest/largest to smallest.

For example, given 8493, I want that number to become 3489.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    Turn the number into a sequence of digits. Sort the sequence. Turn the [sorted] sequence of digits back into a number. The 'code' (and if a separate sequence vs simply a logic one is even used) will vary by language. Note that some numbers like 420 may lose a digit when turning it back into an integer (24). – user2864740 May 11 '15 at 07:07
  • Welcome to Stack Overflow. Please read the [About] page soon. Generally speaking, we'll help you resolve problems in your code, but we won't write code from scratch for you. You would do better to show what you've tried, explaining why it isn't working, showing what it produces for the given input and how that is different from what you expected. You did specify an example input and the corresponding output; that is good. – Jonathan Leffler May 11 '15 at 07:19

2 Answers2

1

Hack the number into digits, sort them and put them back together.

In your case: 8493 -> {8, 4, 9, 3} -> {3, 4, 8, 9} -> 3489

With 2 digits: 51 -> {5, 1} -> {1, 5} -> 15

With 12 digits: 511111011111 -> {5, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1} -> {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5} -> 11111111115 (here it depends if you want to keep the 0 or not.

Burkhard
  • 14,596
  • 22
  • 87
  • 108
  • But its not specified how much characters there are, so i cant do what you said. – Fadi hayik May 11 '15 at 13:10
  • @Fadihayik: why not? If there are 2 characters, you will only have two digits. If there are 20 chars, 20 digits. I'll add another example for clarity. – Burkhard May 11 '15 at 16:15
0

Convert int to string, then use Best way to reverse a string. If needed convert string back to int.

Community
  • 1
  • 1
peterkodermac
  • 318
  • 5
  • 13
  • You might need to explain why reversing a string is relevant to this problem, since sorting is more obviously relevant than reversing. – Jonathan Leffler May 11 '15 at 07:18