Sorting digits of an integer

前端 未结 9 1274
日久生厌
日久生厌 2020-12-16 01:26

You are given an integer 51234 (say) we need to sort the digits of a number the output will be 12345.

How to do it without using array ?

9条回答
  •  臣服心动
    2020-12-16 02:20

    General overview:

    • loop for i = 0 to 9
    • in each loop iteration, walk through the digits in the number (using another loop that does a "mod 10" operation to peel off the digits until the number reduces to zero) - if it matches the digit you're currently working on, print it

    The only potentially tricky bit might be properly handling zeros - you don't want too many, and you'll want to handle the edge case where the input is zero properly.

    Actual implementation is left as an exercise...

提交回复
热议问题