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
题目大意:
123456789是一个9位整数,其中的每位数字在1到9的范围内,它的两倍即246913578,也由相同的1到9中的数字排列组成,即1个1,1个2,1个3......现给你一个由k个数组成的整数(不超过20位),要求你求出该数的两倍是否满足以上条件,若满足输出Yes,否则输出No,并在第二行中输出该数的两倍数。
解题思路:
该题涉及高精度整数(大整数)与低精度整数(基本数据类型)相乘。
首先,由于给出的数字在20位的范围内,而long long最多只能表示19位数,将该数乘以2后更加存储不下,因此在该题中我使用string类型存储输入的数字以及数字两倍的结果;
接着,处理大数与基本数据类型的相乘:只需要将大数的每一位与基本数据类型相乘,用一个变量记录下进位,并用一个string变量存储下每一位相乘的结果即可。
详细算法解释如下:
(摘自胡凡算法笔记5.6.2)
代码如下:
#include<iostream>
#include<algorithm>
using namespace std;
string old;
int number[10] = {0};
int all[10] = {0};
string ans;
void judge(string old){
int carry = 0; //进位
reverse(old.begin(),old.end());//翻转字符串,从低位开始
for(int i = 0 ; i < old.length() ; i ++){
int a = old[i] - '0',b = 2;
int c = a * b + carry;
carry = c / 10;
all[c % 10] ++;
ans += (c % 10) + '0';
}
while(carry){//乘法的进位可能不止一位
all[carry % 10] ++;
ans += (carry % 10) + '0';
carry /= 10;
}
int i = 0;
for(; i <= 9 ; i ++)
if(all[i] != number[i])
break;
if(i < 10)
printf("No\n");
else
printf("Yes\n");
reverse(ans.begin(),ans.end());
cout<<ans;
}
int main(){
cin>>old;
for(int i = 0 ; i < old.length(); i ++)
number[old[i] - '0'] ++;
judge(old);
return 0;
}