题目
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
代码
关于长整数的运算有很多套路,最简便的方法应该是充分使用string类型。
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
string Double(string t){
string n=t;//这一步必须使n=t,否则字符串不分配内存
int i=t.size()-1,add=0;
while(i>=0){
int tem=(t[i]-'0')*2+add;
n[i]=tem%10+'0';
add=tem/10;
i--;
}
if(add) n.insert(0,"1");
return n;
}
int main(){
string t;cin>>t;
string n=Double(t);
if(t.size()!=n.size()){
cout<<"No"<<endl<<n<<endl;return 0;
}
string b=n;
sort(t.begin(),t.end());//当sort所排序的不是数组,不能使用sort(t,t+t.size())这样的写法
sort(n.begin(),n.end());
if(t==n)cout<<"Yes"<<endl;
else cout<<"No"<<endl;
cout<<b<<endl;
return 0;
}