• ZCMU--1379: The Black Hole of Numbers(C语言)


    Description

    For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in non-increasing order first, and then in non-decreasing order, a new number can be obtained by taking the second number from the first one. Repeat in this manner we will soon end up at the number 6174 -- the "black hole" of 4-digit numbers. This number is named Kaprekar Constant.

    For example, start from 6767, we'll get:

    7766 - 6677 = 1089
    9810 - 0189 = 9621
    9621 - 1269 = 8352
    8532 - 2358 = 6174
    7641 - 1467 = 6174

    Given any 4-digit number, you are supposed to illustrate the way it gets into the black hole.

    Input

    Each input file contains one test case which gives a positive integer N in the range (0, 10000).

    Output

    If all the 4 digits of N are the same, print in one line the equation "N - N = 0000". Else print each step of calculation in a line until 6174 comes out as the difference. All the numbers must be printed as 4-digit numbers.

    Sample Input

    6767

    2222

    Sample Output

    7766 - 6677 = 1089

    9810 - 0189 = 9621

    9621 - 1269 = 8352

    8532 - 2358 = 6174

    2222 - 2222 = 0000

    解析:n化为4位数后,n数字降序 — n数字升序,如果结果是0或者是6174,结束。

    注意点:输入n可能小于4位数,如果直接数值型计算需要进行补零,不然会死循环一直输出,导致Output Limit Exceed,不过可以用数组来存一下,排个序,相减的数即x=a[3]*1000+a[2]*100+a[1]*10+a[0];//数字降序
    y=a[0]*1000+a[1]*100+a[2]*10+a[3];//数字升序

    1. #include
    2. int a[4];
    3. int main()
    4. {
    5. int n,i,j,t,x,y;
    6. while(~scanf("%d",&n)){
    7. while(1){
    8. for(i=0;i<4;i++) a[i]=n%10,n/=10;//将数字保存到数组
    9. for(i=0;i<3;i++){ //冒泡从小到大排序(就4个数,当然sort没问题👍)
    10. for(j=i+1;j<4;j++){
    11. if(a[i]>a[j]) t=a[i],a[i]=a[j],a[j]=t;
    12. }
    13. }
    14. x=a[3]*1000+a[2]*100+a[1]*10+a[0];//数字降序
    15. y=a[0]*1000+a[1]*100+a[2]*10+a[3];//数字升序
    16. printf("%04d - %04d = %04d\n",x,y,x-y);
    17. n=x-y;//更新n
    18. if(n==0||n==6174) break;//满足,退出即可
    19. }
    20. }
    21. return 0;
    22. }

  • 相关阅读:
    Python(四)——变量的定义和简单使用
    【疫情防控毕业设计源码】精品微信小程序社区疫情防控+后台管理系统|前后分离VUE[包运行成功]
    Redis集群原理与容器化部署集群
    【nginx】代理配置
    C#中引用类型的变量做为参数在方法调用时加不加 ref 关键字的不同之处
    基于51单片机交通信号灯仿真_东西管制+南北管制
    MATLAB:数组与矩阵
    Adams齿轮副
    软件集成商如何借助小程序降本增效
    Webpack
  • 原文地址:https://blog.csdn.net/qq_63739337/article/details/126326821