POJ 1350-Cabric Number Problem

Cabric Number Problem

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 44   Accepted Submission(s) : 13
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!!


题意:
如果我们输入一个由4位数字构成的数字,而这些数字并非都是相同的值,那么它遵循以下法则。
让我们用以下方法操作这个数字:
(1)将从大到小的数字排列起来,这样就形成了可以由四位数字组成的最大数字;
(2)将小到大的数字排列成数字,这样就可以从4位数字中形成最小的数字(如果4位数字中有0个,则得到的数字可能小于4位);
(3)找出这两个数字的不同,这是一个新的四个数字数字。
重复上述过程,我们最终总能得到结果6174或0。

*这里需注意输入的问题,一定是大于或等于1000小于10000的数,并且不能 4 个数字一样。

如果整数完全由4个数字组成,而这些数字并不是所有相同的值,那么程序的输出应该显示找到这个数字和重复次数的过程。
否则输出”NO! !”

代码中用到的 sscanf 函数和 sprintf 函数具体请看下面链接,详解:


#include <iostream>
#include<string>
#include<string.h>
#include<stdio.h>
#include<algorithm>
using namespace std;

bool cmp(char a,char b)
{
	return a>b;
}

bool book(int &x)///引用,可改变实参的值
{
	int a,b,n;
	char s[11];
	sprintf(s,"%d",x);///把整数x打印成一个字符串保存在s 中
	n=strlen(s);
	sort(s,s+n);
	sscanf(s,"%d",&a);///把s里的字符以数字的形式存入 a
	sort(s,s+n,cmp);
	sscanf(s,"%d",&b);
	printf("%d-%d=%d\n",b,a,b-a);
	x=b-a;
    if (x==6174||x==0)
		return false;
	return true;
}

int main()
{
	int n;
	while (cin>>n,n!=-1)
	{
		printf("N=%d:\n",n);
		int step=1;
		if (n%1111==0||n>9999||n<1000)
		{
			printf("No!!\n");
			continue;
		}
		while (book(n))
			step++;
		printf("Ok!! %d times\n",step);
	}
	return 0;
}


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值