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或者char数组来存的。char数组可以直接用scanf("%s",c)来输入,不用&符号。
用strlen来获取c数组的具体位数,strlen是在string.h头文件中的。
从最后一位开始循环,temp等于当前位的数字,hash[temp]++,因为,要算的是两倍,所以temp=temp*2+进位。然后把进位重置为0,如果temp>=10,那么进位为1,temp=temp-10;最后hash[temp]–,如果最后hash数组不是全为0,证明是No
最后如果hash数组不全为0或者最后一位的进位==1,直接输出no
如果进位为1,最前面还要输出1
#include<iostream>
#include<string.h>
using namespace std;
int main(){
int hash[10]={0}, carry = 0;
bool flag = true;
char c1[22];
scanf("%s",c1);
int len = strlen(c1);
for(int i = len-1; i >= 0; i--){
int temp = c1[i] - '0';
hash[temp]++;
temp = temp*2+carry;
carry = 0;
if(temp >= 10) {
carry = 1;
temp = temp - 10;
}
hash[temp]--;
c1[i] = (temp + '0');
}
for(int i = 0; i < 10; i++){
if(hash[i] != 0) flag = false;
}
if(flag==false || carry==1) cout<<"No"<<endl;
else cout<<"Yes"<<endl;
if(carry == 1)
cout<<"1";
printf("%s",c1);
return 0;
}
二刷
#include<iostream>
using namespace std;
int hashTable[256] = {0};
string doubleit(string a){
string sum = a;
int carry = 0;
for(int i = a.length() - 1; i >= 0; i--){
sum[i] = (a[i] - '0' + a[i] -'0' +carry)%10+'0';
carry = (a[i] - '0' + a[i] -'0'+carry)/10;
}
if(carry == 1) return '1'+sum;
return sum;
}
int main(){
string a;
bool flag = true;
cin>>a;
for(int i = 0; i < a.length(); i++){
hashTable[a[i]]++;
}
string b = doubleit(a);
for(int i = 0; i < b.length(); i++){
hashTable[b[i]]--;
}
for(int i = 0; i < 256;i++){
if(hashTable[i] != 0) flag = false;
}
if(flag == true) cout<<"Yes\n";
else cout<<"No\n";
cout<<b;
return 0;
}