题目
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
答案
#include<iostream>
using namespace std;
int main()
{
int cnt1[10]={0},cnt2[10]={0};
string s,tmp;
cin>>s;
tmp=s;
for(int i=0;i<tmp.length();i++)
{
cnt1[tmp[i]-'0']++;
}
int t1=0,t2=0;
for(int i=tmp.length()-1;i>=0;i--)
{
t1=(tmp[i]-'0')*2+t2;
tmp[i]=t1%10+'0';
t2=t1/10;
}
for(int i=0;i<tmp.length();i++)
{
cnt2[tmp[i]-'0']++;
}
if(t2!=0) cnt2[t2]++;
for(int i=0;i<10;i++)
{
if(cnt1[i]!=cnt2[i])
{
cout<<"No"<<endl;
if(t2!=0) cout<<t2;
cout<<tmp<<endl;
return 0;
}
}
cout<<"Yes"<<endl;
if(t2!=0) cout<<t2;
cout<<tmp<<endl;
}
注意
学过计组的同学应该很清楚,当整形、长整型等类型的变量如果位数超过上限,就会转而变为负数,本题中乘2后就有这个问题
所以我们就要使用字符串存放数字,并且模拟数字乘2的操作,最后要注意进位t2的判断