PAT-A1023 Have Fun with Numbers 题目内容及题解
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
题目大意
题目给定一个大整数,将其乘二,并检验其是否是原数数字的不同排列。
解题思路
- 用字符串形式输入大整数,并将各位数字计数;
- 大整数乘法将其乘二;
- 检验该结果是否为原数字不同排序,输出结果并返回0值;
代码
#include<stdio.h>
void check(char a[],char b[]){
int i=0,num[10]={0,0,0,0,0,0,0,0,0,0};
while(a[i]){
num[a[i++]-'0']++;
}
if(b[i]){
printf("No\n");
return;
}
while(i){
num[b[--i]-'0']--;
if(num[b[i]-'0']<0){
printf("No\n");
return;
}
}
printf("Yes\n");
return;
}
int main(){
char n1[30],n2[30];
int len=0,sum,i,k=0,c=0;
scanf("%s",&n1);
while(n1[len]){
len++;
}
for(i=len-1;i>=0;i--){
sum=(n1[i]-'0')*2+c;
c=sum/10;
sum=sum%10;
n2[k++]=sum+'0';
}
if(c==1){
n2[k++]='1';
}
n2[k]=0;
check(n1,n2);
while(k){
printf("%c",n2[--k]);
}
printf("\n");
return 0;
}
运行结果