7-49 Have Fun with Numbers (20分)
题目描述
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,这恰好是另一个9位数的数字,由1到9的数字组成,只是排列不同。如果我们再加倍检查一下结果!
现在您应该检查这个属性是否有更多的数字。也就是说,把一个给定的数字乘以两倍,再加上k个数字,你就可以知道得到的数字是否只由原始数字中的数字排列而成。
输入规格:
每个输入包含一个测试用例。每个大小写包含一个不超过20位的正整数。
输出规格:
对于每一个测试用例,如果输入的数字加倍,则第一次在“是”行中打印一个数字,该数字仅由原始数字中的数字排列而成,否则为“否”。然后在下一行中,打印加倍的数字。
思路
由于限制是不超过20位的数字,若采用整形会造成越界问题,所以采用字符数组来存储大数并模拟大数的乘2运算
如果第一位的数>=5,会产生进位,可以先保存该位,然后从最后一位计算,如果乘2之后>=10,那么进1,否则,不进
#include <stdio.h>
#include <string.h>
#define N 21
int main (){
char start[N],end[N];
gets(start); //输入
int t,i,j,m=0,s;
int flag=0,flag1=0;
//flag标记是否有进位,flag1标记是否与原数中各数数量相等
t=strlen(start); //位数
//判断第一位大于5时进位
if((start[0]-'0')*2>=10){
end[0]='1'; //乘2只可能进一位
flag=1; //有进位,一定不等于原数
}
for(i=t-1; i>=0; i--){ //做运算
if((start[i]-'0')*2>=10){
s=(start[i]-'0')*2%10+m;
end[i+1]='0'+s;
m=1; //进位
}
else{
s=(start[i]-'0')*2+m;
end[i+1]='0'+s;
m=0; //不进位
}
}
flag1=1; //假设两数相等,找出不相等
for(i=1; i<=t; i++){ //遍历end数组
for(j=0; j<t; j++){
if(end[i]==start[j]){ //判断是否有两数相等
start[j]='a'; //若有两数相等,在start数组中变为a
break;
}
}
}
//若start数组中不全为a,则end数组中有与start数组中不相等的数
for(i=0; i<t; i++){
if(start[i]!='a'){
flag1=0; //标记该结果
break;
}
}
if(flag1==1)
printf("Yes\n");
else
printf("No\n");
if(flag==1){
for(i=0; i<=t; i++){ //有进位从第一位输出
printf("%c",end[i]);
}
}
else{
for(i=1; i<=t; i++){ //无进位从第二位输出
printf("%c",end[i]);
}
}
return 0;
}