Sorting digits of an integer

前端 未结 9 1257
日久生厌
日久生厌 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...

    0 讨论(0)
  • 2020-12-16 02:20

    You don't need to write a program at all, just do it with shell commands:

    echo "51234" | sed 's+\(.\)+\1\n+g' | sort | tr -d '\n'
    
    0 讨论(0)
  • 2020-12-16 02:21

    Create a container interface over the int (something like vector), where operator references the i'th decimal digit. You would have to define iterators and other things too. Then call std::sort on it. ;)

    0 讨论(0)
提交回复
热议问题