题目链接

Description

If we input a number formed by 4 digits and these digits are not all of one same value, then it obeys the following law. Let us operate the number in the following way:
(1) Arrange the digits in the way from bigger to smaller, such that it forms the biggest number that could be made from these 4 digits;
(2) Arrange the digits in the way from smaller to bigger, such that it forms the smallest number that could be made from these 4 digits (If there is 0 among these 4 digits, the number obtained may be less than four digits);
(3) Find the difference of these two numbers that is a new four digital number.
Repeat the above process, we can finally always get the result 6174 or 0.
Please write the program to realize the above algorithm.

Input

Each case is a line of an integer.-1 denotes the end of input.

Output

If the integer is formed exactly by 4 digits and these digits are not all of one same value, then output from the program should show the procedure for finding this number and the number of repetition times. Otherwise output "No!!".

Sample Input

5364
2221
4444
-1

Sample Output

N=5364:
6543-3456=3087
8730-378=8352
8532-2358=6174
Ok!! 3 times
N=2221:
2221-1222=999
999-999=0
Ok!! 2 times
N=4444:
No!!

分析:
题目会给定一个四位数字,将每个数位上的数字重新排列组合后,能够组成一个最大的四位数和最小的四位数。将求差之后的结果接着进行计算,直到答案为6174或则为0.

注意:最开始输进去的一个是四位数,切四个位数不能够全部相等。
中间计算后的结果可能不是四位数字,所以如果按照四位数字计算的话,得去掉所有的前导0.

代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int cant(int s)//判断四个位置上的数字是否完全相同
{
    int a=s/1000;
    int b=s/100%10;
    int c=s/10%10;
    int d=s%10;
    if(a==b&&b==c&&c==d) return 1;
    return 0;
}
int cal(int s)//s传进来的是每次计算后得到的结果
{
    int a[4];
    a[0]=s/1000;
    a[1]=s/100%10;
    a[2]=s/10%10;
    a[3]=s%10;
    int fl=0;//表示的是这个计算结果中前导0的个数
    if(a[0]==0)
    {
        fl=1;
        if(a[1]==0)
        {
            fl=2;
            if(a[2]=0)fl=3;
        }
    }
    sort(a,a+4);//从小到大排序
    int max_num,min_num;
    min_num=a[0]*1000+a[1]*100+a[2]*10+a[3];
    // 处理高位为0的情况
    if(fl==0)
    {
        max_num=a[3]*1000+a[2]*100+a[1]*10+a[0];
    }
    else if(fl==1)
    {
        max_num=a[3]*100+a[2]*10+a[1];
    }
    else if(fl==2)
    {
        max_num=a[3]*10+a[2];
    }
    else
    {
        max_num=a[3];
    }
    printf("%d-%d=%d\n",max_num,min_num,max_num-min_num);
    return max_num-min_num;
}
int main()
{
    int n;
    while(~scanf("%d",&n)&&n!=-1)
    {
        printf("N=%d:\n",n);
        if(n>=9999||n<=1000||cant(n)) //注意,输入一定要是4位数,并且四个位置上的数字不能全部相同
        {
            printf("No!!\n");
            continue;
        }
        int ans=0;
        while(n!=0&&n!=6174)
        {
            ans++;
            n=cal(n);
        }
        printf("Ok!! %d times\n",ans);
    }
    return 0;
}
posted on 2017-10-15 15:15  渡……  阅读(122)  评论(0编辑  收藏  举报