Cabric Number Problem
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!! Source |
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int cmp(const void*a,const void*b)
{
return *(int *)a-*(int *)b;
}
int sum1(int a[],int n)
{
if(n==4) return 1000*a[0]+100*a[1]+10*a[2]+a[3];
else if(n==3) return 100*a[0]+10*a[1]+a[2];
else if(n==2) return 10*a[0]+a[1];
else if(n==1) return a[0];
}
int sum2(int a[],int n)
{
if(n==4) return 1000*a[3]+100*a[2]+10*a[1]+a[0];
else if(n==3) return 100*a[2]+10*a[1]+a[0];
else if(n==2) return 10*a[1]+a[0];
else if(n==1) return a[0];
}
int main()
{
int number;
//freopen("in.txt","r",stdin);
while(~scanf("%d",&number)&&number!=-1)
{
int a[4],digit1,digit2,s,ss,numbers,times=0,t=4;
numbers=number;
cout<<"N="<<number<<":"<<endl;
if(number<=999||number>=10000) /*不满足四位数跳出*/
{
printf("No!!\n");
continue;
}
for(int i=0; i<4; i++)
{
a[i]=number%10;
number/=10;
}
if(a[0]==a[1]&&a[1]==a[2]&&a[2]==a[3]) /*全相等的时候直接输出N哦!!跳出*/
{
printf("No!!\n");
continue;
}
do
{
int b[4];
for(int i=0; i<t; i++)
{
b[i]=numbers%10;
numbers/=10;
}
qsort(b,t,sizeof(int),cmp); /*排序*/
digit1=sum2(b,t);
digit2=sum1(b,t);
s=digit1-digit2;
printf("%d-%d=%d\n",digit1,digit2,s);
ss=numbers=s;
times++;
for(t=0; ss!=0; t++) ss/=10; /*t用来存位数*/
}
while(s!=0&&s!=6174);
printf("Ok!! %d times\n",times);
}
return 0;
}