1023 Have Fun with Numbers (20分)【大整数的运算】

1023 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

解题思路:

这道题说的是给定我们一个长度不超过20的整数,问这个整数的两倍后的数位是否为原数位的排列。很明显不超过20的长度不要说int类型的-2\times10^9~2\times10^9 ,连longlong类型的-9\times10^{18}~9\times10^{18},也是不够的,因此肯定得使用大整数的运算。这里我们可以直接使用string类型来存储。

注意:如果新的数的长度和原来数的长度不一样,那么一定是No。

#include<iostream>
#include<string>
using namespace std;

int main()
{
	int cnt1[10] = { 0 }, cnt2[10] = { 0 };  //统计各个数的出现次数
	string num1, num2 = "";
	cin >> num1;
	int len1 = num1.length();
	int s = 0;   //进位位
	for (int i = len1 - 1; i >= 0; i--)
	{
		cnt1[num1[i] - '0']++;
		int num = num1[i] - '0';
		int tmp = num * 2 + s;
		s = tmp / 10;
		int c = tmp % 10+'0';
		num2 = (char)c + num2;
	}
	if (s != 0)
		num2 = (char)(s + '0') + num2;
	for (int i = 0; i < num2.length(); i++)
		cnt2[num2[i] - '0']++;
	int flag = 1;
	for (int i = 0; i < 10; i++)
	{
		if (cnt1[i] != cnt2[i])
		{
			flag = 0;
			break;
		}
	}
	if (num2.length() != len1||flag==0)
		cout << "No" << endl;
	else
		cout << "Yes" << endl;
	cout << num2 << endl;
	return 0;
}

 

posted @ 2020-04-15 12:30  Hu_YaYa  阅读(25)  评论(0)    收藏  举报