题目
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
背景
额,这道题在我大一时就遇到了。当时才学c语言,用的是笨办法,结果是部分正确。由于考研需要,近期重返了c语言,虽然二年没摸c语言了,但是由于大一时苦练,很快就拾起来了。现在看到这个题目时,觉得当年的代码写的跟**一样。不过我也感谢大一时的坚持。很快,我对这题就有了新的思路。
新的思路
总体思路
统计乘积前和乘积后序列各数字的频度,然后进行比较频度即可。
细说:
由于数字只有0-9,且序列长度不会超过20。所以用一有10个有效字符的字符数组存储频度即可。这样空间复杂度为O(1)。时间复杂度为O(n)。
#include"stdio.h"
#include"string.h"
int main(){
char array[21]="\0";//保存原序列,经算法后,保存的是乘积后的序列。(若最高位溢出,不保存溢出位1。)
gets(array);
char freq[2][11]={"\0","\0"};//一维保存原序列个数字出现的频度,二维保存乘积后各数字出现的频度
int length=strlen(array);
int j=0;//工具
int overFlow=0;//某位乘积加上低位进位后是否溢出。0位没溢出,1位溢出。
int i=length - 1;
while(i>=0){
j=array[i]-'0';
freq[0][j]+=1;//原序列 相应数字频度+1
j=j*2;//单位数乘2
if(overFlow==1){
j++;
overFlow=0;
}
//处理进位。找到不为9的前一位
if(j>9){
j=j%10;//产生乘积后的个位数字。
overFlow=1;
}
freq[1][j]+=1;//乘积后个位数字的频度加1。有了上面if,保证了0=<j<=9
array[i]=j+'0';
i--;
}
//对比各数字频度是否相等
for(int x=0;x<10;x++){
if(freq[0][x]!=freq[1][x]){
printf("No\n");
break;
}
if(x==9)
printf("Yes\n");
}
if(overFlow==1){
printf("1");
}
puts(array);
return 0;
}