PAT 1023. 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 file 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位的数,然后乘2,然后判断结果的数是不是由原来的数的各位数字的组合。
分析
这道题20位的运算超出了usigned long long,故需要模拟运算。
关于是否是原来的数个位数字的不同排列我用的是一个数组来记录原来数的各位数字出现的次数,然后再和后来double后的对比就可以了。
#include<iostream>
using namespace std;
int main(){
string s,double_s;
cin>>s;
int a[10]={0},add=0,digit;
for(int i=s.size()-1;i>=0;i--){
a[s[i]-'0']++;
digit=((s[i]-'0')*2+add)%10;
add=((s[i]-'0')*2+add)/10;
double_s.insert(double_s.begin(),1,'0'+digit);
a[digit]--;
}
if(add>0){
double_s.insert(double_s.begin(),1,'0'+add);
a[add]--;
}
int flag=1;
for(int i=0;i<10;i++)
if(a[i]!=0) flag=0;
flag>0?cout<<"Yes"<<endl:cout<<"No"<<endl;
cout<<double_s<<endl;
return 0;
}