题目:(大整数用字符数组存储)
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 <stdio.h>
#include <string.h>
#define N 21
int main(){
char original[N];
int doubledNum[N], i, digitsCount[10];
int carry=0, isSame=1; //记录原始大数乘以2后是否产生进位
gets(original);
for(i=0;i<strlen(original);i++){ //得到每位乘2的未处理进位的数
doubledNum[i] = 2*(original[i]-'0');
}
for(i=strlen(original)-1;i>=0;i--){
if(i>0){
doubledNum[i-1] += doubledNum[i]/10;
doubledNum[i] %= 10;
}
else{
carry += doubledNum[i]/10;
doubledNum[i] %= 10;
}
}
if(carry){
isSame = 0;
}
else{
for(i=0;i<10;i++){ //初始化10个位值的计数数组
digitsCount[i] = 0;
}
for(i=0;i<strlen(original);i++){ //逐位增加计数
digitsCount[original[i]-'0']++;
}
for(i=0;i<strlen(original);i++){ //逐位消减计数
digitsCount[doubledNum[i]]--;
}
for(i=0; i<10; i++){ //检查各个位值的计数
if(digitsCount[i]!=0){
isSame = 0;
break;
}
}
}
if(isSame){
printf("Yes\n");
}
else{
printf("No\n");
}
if(carry){
printf("%d", carry);
}
for(i=0;i<strlen(original);i++){
printf("%d", doubledNum[i]);
}
return 0;
}