POJ 1350 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!!
#include<stdio.h>
#include<algorithm>
using namespace std;
char s[100];
int a[100];

bool cmp(const int&a,const int&b)
{
	return a>b;
}

int get(int a[100])
{
	int sum1=0,sum2=0,sum,j;
	for (j=0;!a[j];j++);
	sort(a+j,a+4);
	for (int i=j;i<4;i++)sum1=sum1*10+a[i];
	sort(a+j,a+4,cmp);
	for (int i=j;i<4;i++)sum2=sum2*10+a[i];
	sum=sum2-sum1;
	a[0]=sum/1000;
	a[1]=(sum/100)%10;
	a[2]=(sum/10)%10;
	a[3]=sum%10;
	printf("%d-%d=%d\n",sum2,sum1,sum);
	return sum;
}

int main()
{
	while (~scanf("%s",s))
	{
		if (s[0]=='-'&&s[1]=='1') break;
		printf("N=%s:\n",s);
		int tot=0,sum=0;
		for (int i=0;s[i];i++)
			if (s[i]>='0'&&s[i]<='9') a[tot++]=s[i]-'0';
		sort(a,a+tot);
		if (tot!=4||a[0]==a[tot-1]) 
		{printf("No!!\n"); continue;}
		else tot=0;

		do
		{
			sum=get(a);
			tot++;
		}while (sum!=6174&&sum!=0);
		printf("Ok!! %d times\n",tot);
	}
}

你可能感兴趣的:(poj)