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.
Each input contains one test case. Each case contains one positive integer with no more than 20 digits.
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.
1234567899
Yes
2469135798
输入一个数字X,X乘以2后得到的数字Y,如果Y就是X的各位上的数字重新排列后的结果,则输出YES,否则输出NO.
因为输入样例最大不超过20位,而最大的long long 却仅有 2^64 = 1.844674407371 * 10 19,故需使用字符串来输入数字
原文链接
注意要进位!!!
#include
using namespace std;
string s,s2;
int arr1[10]={0},arr2[10]={0};
int main(){
getline(cin,s);// 1234567899
int len=s.size();
for(int i=0;i<len;++i){
arr1[s[i]-'0']++; //计算数值出现了几次
}
//要考虑进位 ,从后往前
int f=0;
for(int i=len-1;i>=0;i--){
int x=2*(s[i]-'0')+f; //先乘 2 再进位
f=x/10; //x=13 f=1
x=x%10; //x=13 x=3
arr2[x]++;
s2+=x+'0'; // '0'+1='1' 8975319642
}
if(f){
s2+=f+'0';
arr2[f]++; //如果最后一个计算是进位的,那就把进位的也安排了
}
f=1; //f当作flag
for(int i=0;i<10;i++){
if(arr1[i]!=arr2[i]){
f=0;
}
}
if(f){
cout<<"Yes\n";
}else{
cout<<"No\n";
}
for(int i=s2.size()-1;i>=0;i--){
cout<<s2[i];
}
}