c++ - 对整数的数字进行排序

标签 c++ c

给你一个整数51234(比如说)我们需要对一个数字的数字进行排序,输出将是12345

不使用数组怎么办?

最佳答案

您可以使用循环和 % 10 来提取每个数字。 可以使用从 0 到 9 的外循环来测试该数字是否存在。如果存在,请打印。

在伪代码中:

n = integer // 51234
FOR digit = 0 TO 9
  temp = n
  REPEAT
    IF temp % 10 = digit THEN PRINT digit
    temp /= 10
  UNTIL temp = 0

编辑: gcc 中的这个测试表明它可以处理零和重复数字:

$ cat sortdigits.c
#include <stdio.h>
main () {
 int n,digit,temp;
 n = 43042025;
 for (digit=0;digit<9;digit++)
   for (temp=n;temp>0;temp/=10)
     if (temp%10==digit) printf("%d",digit);
 printf("\n");
}
$ ./sortdigits
00223445

关于c++ - 对整数的数字进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2130712/

相关文章:

c - 使用结构变量数组访问结构

c++ - wchar_t* 到字符串的转换

c++ - 延长对象生命周期

c - 在头文件中使用 "extern const"使全局变量只读

控制流程: %rsp and return address and space provided within stack

Xcode 上的 C 编程 - EXC_BAD_ACCESS

c - 函数 getInput 有什么问题?

c++ - Makefile 不理解 g++ 但终端可以

c++ - 这是一个 nullptr 吗?

python - SWIG 将 map vector 转换为 python 字典列表