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.
(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!!
给一个四位数,每位的数字排序后得到一个最大的四位数一个最小四位数,得到的差继续这样操作,直到最后的差是0或6174输出yes和共进行几步输入必须为4位数否则输出no
运算过程中的差可以为3位数
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<queue>
#include<cstdlib>
#include<map>
using namespace std;
int a[10];//存每位数字
int qs(int n)//保存每位数字
{
int i=0;
while(n)
{
a[i]=n%10;
n=n/10;
i++;
}
sort(a,a+i);
return i;
}
int ma(int i)//最大数
{
int s=0;
for(int j=i-1;j>=0;j--)
s=s*10+a[j];
return s;
}
int mi(int i)//最小数
{
int s=0;
for(int j=0;j<i;j++)
s=s*10+a[j];
return s;
}
int main()
{
int n,m;
while(~scanf("%d",&n))
{
if(n==-1)
break;
int t=0;
printf("N=%d:\n",n);
while(1)
{
if(t==0&&(n%1111==0||n<1000||n>9999))
{
printf("No!!\n");
break;
}
int i=qs(n);
int mai=ma(i);
int mii=mi(i);
n=mai-mii;
printf("%d-%d=%d\n",mai,mii,n);
t++;
if(n==0||n==6174)
break;
}
if(t!=0)
printf("Ok!! %d times\n",t);
}
}