【PTA】Have Fun with Numbers

7-49 Have Fun with Numbers(20 分)

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

思路:

  • 写代码遇到的第一个问题是数据类型的问题,刚开始的时候用long long,long long可表示的最大值为19位,测试点不过。改用字符串数组。
  • 那么接下来就要模拟乘法,算出大数的两倍。要注意,最高位可能进位,位数会加1。
  • 之后是判断两个数组中的数字是否相同,最开始的时候我用的方法是,在原始数组中确定一个数,在两倍数组查找,看是否能找到。后来测试点不过,这样忽略了在数组中相同的数字出现不止一次的情况。后来改为找到后,把两倍数组变为字符‘a’,当然要提前保存一下数组,之后在遍历数组判断是否全为'a'即可。

代码: 

#include <stdio.h>
#include <string.h>
const int num=21;
int main(int argc,const char*argv[])
{
	char a[num];
	gets(a);//获得大数 
	char ta[num];
	int flag=0;
    if((a[0]-'0')>=5)//如果第一位的数字大于5,进位为1 
	{
    	ta[0]=1;
    	flag=1;
	}else
	{
		ta[0]=0;
	}
	for(int i=strlen(a)-1;i>=0;i--)//模拟乘法 
	{
		ta[i+1]=(a[i]-'0')*2%10;
		if(i<strlen(a)-1)//当不是最后一位数字时 
		{
			ta[i+1]+=(a[i+1]-'0')*2/10;
		}
	}
	char b[num];
	for(int ii=0;ii<=strlen(a);ii++)//中间操作会破坏数组,所以拷贝给另一个数组 
	{
		b[ii]=ta[ii];
	}
	for(int j=0;j<strlen(a);j++)
	{
		if(flag==0)//位数相同时 
		{
			for(int jj=1;jj<=strlen(a);jj++)
			{
				if((a[j]-'0')==ta[jj])
				{
					ta[jj]='a';//把每一位相同的数字都变为a 
					break;	
				}
			}
		}else//如果位数不一样,直接退出 
		{
			break;
		}
	}
	int mark=0;
	for(int m=1;m<=strlen(a);m++)//遍历数组,检查是否所有的都为a 
	{
		if(ta[m]!='a')
		{
			printf("No\n");
			mark=1;
			break;
		}
	}
	if(mark==0)
	{
		printf("Yes\n");
	}
	for(int n=0;n<=strlen(a);n++)
	{
		if(n==0&&b[0]==0)
		{
			n++; 
		}
		printf("%d",b[n]);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/jiangxiaoshan123/article/details/81634719