一、题目
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 file 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.
二、题意理解
给出一个不超过20位的数字,将其翻倍,判断翻倍后的数字是否能由原有数字的数位重排列得到。
三、算法思想
1、由于数字位数最多可达20位,在某些case中使用整型存储数字会溢出,故采用字符数组存储。
2、翻倍后的数字可能比原有数字多一位,故存储翻倍后数字的数组需将首位预留出来。
3、判断两个数字是否能通过重排列互相转换时,可先根据数字的位数作判断,若位数不同则直接下结论,若位数相同,则将存储两个数字的字符数组进行排序,再比对排序后的数组中的每一位元素是否相等。
四、C语言实现
#include <stdio.h>
#define size 21 //存储数字的字符数组大小
void SortChar(char *A,int n)//对字符数组升序排列
{
int i,j;
char t;
for(i=2;i<=n;++i){
t=A[i];
for(j=i;j>=2&&t<A[j-1];--j){
A[j]=A[j-1];
}
A[j]=t;
}
}
void PrintArray(char *A,int oldn,int newn)//打印数字
{
int i;
for(i=oldn-newn+1;i<=oldn;++i)//根据翻倍后数字和原数字的位数来决定从数组中哪一个位置开始打印
printf("%c",A[i]);
printf("\n");
}
int IsRight(char *Ar,char *doubleAr,int n)//比对排序后的两字符数组的对应元素
{
SortChar(Ar,n);
SortChar(doubleAr,n);
int i;
for(i=1;i<=n;++i)
if(Ar[i]!=doubleAr[i])
return 0;
return 1;
}
int main()
{
char Ar[size],doubleAr[size],temp[size];//原数字,翻倍后数字,由于前两个数组会进行排序,翻倍结果还需一个数组保存
char c;
int i=1,oldn=0,newn,digit,cur=0;
while((c=getchar())!='\n'){//读取数位,从数组中下标为1的位置开始存储
Ar[i++]=c;
oldn++;//统计位数
}
for(i=oldn;i>=1;--i){//翻倍
digit=Ar[i]-'0';
digit=digit*2+cur;
doubleAr[i]='0'+digit%10;
temp[i]=doubleAr[i];
cur=digit/10;
}
if(cur){//最高位有进位
doubleAr[0]=cur+'0';
temp[0]=cur+'0';
newn=oldn+1;//新数字比原数字多一位
}else
newn=oldn;
if(newn!=oldn||!IsRight(Ar,doubleAr,newn)){
printf("No\n");
}else
printf("Yes\n");
PrintArray(temp,oldn,newn);
return 0;
}