如何按从小到大的顺序对数字的数字进行排序?

时间:2022-02-26 20:25:01

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.

例如,鉴于8493,我希望该数字变为3489。

2 个解决方案

#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

在你的情况下:8493 - > {8,4,9,3} - > {3,4,8,9} - > 3489

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

有2位数: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.

12位数: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(这取决于你是否要保留0或者不是。

#2


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

将int转换为string,然后使用Best方法反转字符串。如果需要将字符串转换回int。

#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

在你的情况下:8493 - > {8,4,9,3} - > {3,4,8,9} - > 3489

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

有2位数: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.

12位数: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(这取决于你是否要保留0或者不是。

#2


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

将int转换为string,然后使用Best方法反转字符串。如果需要将字符串转换回int。