C语言 Have Fun with Numbers

Have Fun with Numbers

原文:

Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it again!
Now you are suppose to check if there are more numbers with this property. That is, double a given number with k digits, you are to tell if the resulting number consists of only a permutation of the digits in the original number.
Input Specification:
Each input contains one test case. Each case contains one positive integer with no more than 20 digits.
Output Specification:
For each test case, first print in a line “Yes” if doubling the input number gives a number that consists of only a permutation of the digits in the original number, or “No” if not. Then in the next line, print the doubled number.

Sample Input:

1234567899

Sample Output:

Yes
2469135798

译文:
数字带来的乐趣
请注意,数字123456789是一个9位数字,恰好由1到9的数字组成,没有重复。我们将得到246913578,这是另一个9位数,恰好由1到9之间的数组成,只是排列方式不同。如果我们再次翻倍,检查看看结果!
现在您应该检查这个属性是否有更多的数字。也就是说,对一个给定的 k 位数进行加倍处理,就可以知道结果数是否只包含原始数中的数字的排列。
输入格式:
每个输入包含一个测试用例,每个用例包含一个不超过20位的正整数。
输出格式:
对于每个测试用例,如果将输入数字加倍得到的数字仅由原始数字的排列组成,则在第一行中打印“ Yes” ,如果不是,则打印“ No”。然后在下一行,打印两倍的数字。
输入样例:
1234567899
输出样例:
Yes
2469135798

思路分析:
1、通过strlen()函数得出其位数,将其由字符型转化为整数型,并统计原数据中每个数字出现的次数。
2、将原数据加倍并,将加倍后的新数据中的数字进行次数统计,将其由整数型转化为字符型。
3、判断是否有新增加位数和逢十进一的情况。
4、对比原数据与新数据,输出结果。

代码如下:

#include "stdio.h"
#include "string.h"
void number()
{
	char m[21];
	int n,k,b[21]={0};//b[21]={0}将数组初始化 
	int i,j=0,num=0,flag=0;
	scanf("%s",m);
	n=strlen(m);//得出该整数的位数
	for(i=n-1; i>=0; i--)
	{
		k=m[i]-'0';//将数据由字符型转化成整数型
		b[k]++;//每个数字出现的次数所组成的数组
		k=k*2+num; //将每个数字加倍,若加倍后小于10num为0,反则num=1,即逢十进一
		num=0;
	//	j++;
		if(k>=10)//逢十进一
		{
			k-=10;
			num=1;
		}
		m[i]=k+'0';//将转化后的数据由整数型转化成字符型
		b[k]--;//加倍后每个数字出现的次数是否对应原数据中数字出现的次数,对应则消去
	}
	for(i=0; i<10; i++)
	{
		if(b[i]!=0)//不为零则含有有原数据中没有的数字
		{
			flag=1;
			break;
		}
	}
	if(flag==0)//加倍后的数据与原数据中所包含的数字相同 
		printf("Yes\n");
	else
		printf("No\n");
	if(num==1)//加倍后位数增加,第一位为1,其余往后退一位 
		printf("1");
	printf("%s\n",m);
}
int main()
{
	number();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/AMCUL/article/details/108173435