• 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. }

  • 相关阅读:
    MyBatis resultMap元素
    互联网时代,企业如何扭转线下采购劣势?
    element-ui upload图片上传组件使用
    Leetcode 算法面试冲刺 热题 HOT 100 刷题(300 301 309 312 322)(六十七)
    使用LabVIEW实现基于pytorch的DeepLabv3图像语义分割
    每日一题~组合总数III
    论文生成器(论文、文献综述、开题报告……),Java、Python、C++
    ChatGPT追祖寻宗:GPT-2论文要点解读
    随处可见的红黑树
    架构每日一学 14:架构师如何进行可行性探索?
  • 原文地址:https://blog.csdn.net/qq_63739337/article/details/126326821