• NYOJ 57 6174问题


    6174问题

    时间限制:1000 ms  |  内存限制:65535 KB
    难度:2
     
    描述

    假设你有一个各位数字互不相同的四位数,把所有的数字从大到小排序后得到a,从小到大后得到b,然后用a-b替换原来这个数,并且继续操作。例如,从1234出发,依次可以得到4321-1234=3087、8730-378=8352、8532-2358=6174,又回到了它自己!现在要你写一个程序来判断一个四位数经过多少次这样的操作能出现循环,并且求出操作的次数

    比如输入1234执行顺序是1234->3087->8352->6174->6174,输出是4

     
    输入
    第一行输入n,代表有n组测试数据。
    接下来n行每行都写一个各位数字互不相同的四位数
    输出
    经过多少次上面描述的操作才能出现循环
    样例输入
    1
    1234
    样例输出
    4

     1 #include<iostream>
     2 #include<algorithm>
     3 #include<string.h>
     4 using namespace std;
     5 char a[5],b[5];int ia,ib;
     6 
     7 int main()
     8 {
     9     int N,count,temp=0;
    10     cin>>N;
    11     while(N--)
    12     {
    13         count=0;
    14         for(int i=0;i<4;i++)
    15             cin>>a[i];
    16     loop:
    17         ia=ib=0;
    18         sort(a,a+4);
    19         for(int i=0;i<4;i++)
    20         {
    21             ia*=10;
    22             ia+=(a[i]-'0');
    23         }
    24         for(int i=3;i>=0;i--)
    25         {
    26             ib*=10;
    27             ib+=(a[i]-'0');
    28         }
    29         ib=ib-ia;
    30         count++;
    31         if(temp!=ib)
    32         {
    33             temp=ib;
    34         for(int i=0;i<4;i++)
    35         {
    36             a[i]=(ib%10+'0');
    37             ib/=10;
    38         }
    39             goto loop;
    40         }
    41         else
    42         {
    43             cout<<count<<endl;
    44         }
    45     }
    46 
    47 }
     1 #include<iostream>
     2 #include<algorithm>
     3 #include<stdio.h>
     4 using namespace std;
     5 int main()
     6 {
     7     int k;
     8     cin>>k;
     9     while(k--)
    10     {
    11         int n,a[4],n1,n2;
    12         scanf("%d",&n);
    13         int s=1;
    14         while(n!=6174)
    15         {
    16             a[0]=n%10;
    17             a[3]=n/1000;
    18             a[1]=n/10%10;
    19             a[2]=n/100%10;
    20             sort(a,a+4);
    21             n1=1000*a[3]+100*a[2]+10*a[1]+a[0];
    22             n2=1000*a[0]+100*a[1]+10*a[2]+a[3];
    23             n=n1-n2;
    24             s++;
    25         }
    26         printf("%d
    ",s);
    27     }
    28 }        
  • 相关阅读:
    JavaScript-数学对象与定时器
    JavaScript(八)-字符串与数组
    嵌入式的笔试题目(1)
    更改登录使用的默认shell的方法
    查看当前Linux 命令行使用的shell 的方法
    启动引导程序 Bootloader
    Debian 系(Deepin, Ubuntu, Linuxmint等)包管理工具
    ubuntu 服务器 samba 局域网内 如何添加samba user
    win10 和 树莓派3b+ 处于同一wifi环境(同一网段), win10 无法ping 通 树莓派3b+
    数据结构概念
  • 原文地址:https://www.cnblogs.com/ljwTiey/p/4305076.html
Copyright © 2020-2023  润新知