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.
Sample Input:
1234567899
Sample Output:
Yes
2469135798
算法分析:由于输入的整数过大,需要存在字符串中,由自己来构造乘法运算。然后创造一个集合collected[10],收录字符串中每个数字的个数。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char num[21] = {'\0'};
int collected[10] = {0};
int n, i, q = 0; //q表示进位多少
gets(num);
n = strlen(num);
for(i = n - 1; i >= 0; i--)
{
int k = num[i] - '0';
collected[k]++; //将每一位收入集合
k = k * 2 + q;
q = 0;
if(k > 9) //判断是否需要进位
{
k = k % 10;
q = 1;
}
num[i] = k + '0';
collected[num[i] - '0']--; //从集合中提取一个数字
//要想符合原数字的一个序列,则集合中每个数字的个数在循环结束时都为0
}
if(q) //多了一位数,肯定不符合
{
printf("No\n");
printf("1%s", num);
}
else
{
for(i = 0; i < 10; i++)
if(collected[i] != 0)
break;
if(i < 10) //判断是否是原数字的一个序列
printf("No\n");
else
printf("Yes\n");
printf("%s", num);
}
return 0;
}