题目介绍
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
注解
要用【高精度乘法】的写法来解这道题,这就是这题的坑点。
题中说“Each case contains one positive integer with no more than 20 digits.”,不超过20位,那就是小于等于20位了。
最开始我是抱着比较侥幸的心理,觉得如果需要【高精度加法】,怎么也得给我来个100位,才20位,有可能只是一说,其实里面没有那么边界的案例。
谁知最后被卡死了,细细推究,也是这样。
哪怕用存储量最大的Long Long,64位,在正数方向最大不过2^63-1 = 9,223,372,036,854,775,807
一共19位,一旦输入量超过这个数,在 这个数~99,999,999,999,999,999,999 范围内,那便溢出了。
而且,后面的乘2,如果用long long来存储,翻了倍,自然更容易溢出。
所以,为了防止溢出,便是要采用【高精度乘法】来写了。
代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1;
cin>>s1;
int t[30]={0}; //用于N的存储
int digit[10] = {0}; //用于判断匹配
int len = s1.size(); //把输入数据用int数组存储起来
for(int i=len-1;i>=0;i--)
{
t[len-i-1] = s1[i]-'0';
digit[s1[i]-'0']++;
}
//计算翻倍后的结果
for(int i=0;i<len;i++) t[i]*=2;
for(int i=0;i<len;i++)
{
t[i+1] += t[i]/10;
t[i] = t[i]%10;
}
if(t[len]!=0) len++;
for(int i=0;i<len;i++)
{
digit[t[i]]--;
}
int flag=0;
for(int i=0;i<10;i++)
{
if(digit[i]!=0) //说明不匹配
{
flag = 1;
break;
}
}
cout<<(flag==0? "Yes" : "No")<<endl;
for(int i=len-1;i>=0;i--) cout<<t[i];
return 0;
}