自测-4 Have Fun with Numbers (20 分)(思路及完整C代码)

自测-4 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

思路:因为数字特别大,所以没办法用常规的int等类型变量来直接存放。所以关键在于独立存放每个数位上的数字。然后在*2的时候需要注意进位的问题。

完整代码:

#include
int main()
{
    int N[21] = { 0 };//分别存放输入数
	int R[21] = { 0 };//存放*2结果
	int count1[10] = { 0 };
	int count2[10] = { 0 };//分别记录数字个数
	int size = 0;//输入位数
	int temp = 0;//存放临时变量
	int out = 0;//乘以2时的进位
	int flag = 0;//flag=0输入YES,否则输入NO
	char c;
	c = getchar();
	while (c != '\n')
	{
		size++;
		N[size] = c - '0';
		count1[c - '0']++;
		c = getchar();
	}

	for (int i = size ; i >= 0; i--)
	{
		R[i] = N[i] * 2%10+ out;
		out = N[i] * 2/10;
	}
	for (int i = size; i > 0; i--)
	{
		count2[R[i]]++;
	}
	if(R[0]!=0)
		count2[R[0]]++;

	for (int i = 0; i < 10; i++)
	{
		if (count1[i] != count2[i])
			flag = 1;
	}
	if (flag == 0)
		printf("Yes\n");
	else
		printf("No\n");
	//输出*2的结果
	if (R[0] != 0)
		printf("%d", R[0]);
	for (int i = 1; i <=size; i++)
	{
		printf("%d", R[i]);
	}
    
}

 

你可能感兴趣的:(pat练习题)