这题不难,主要看了一下,网上好像没有按我这脑回路做的,就记一下吧。
自测-4 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
/**< https://pintia.cn/problem-sets/17/problems/263*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/**< 判断数字出现次数 */
int timesOfNum(int a[], int len, int n);
int main()
{
bool isFun = true;
int maxDigit = 21;
int len = 0;
char a[maxDigit];
int b[maxDigit];
int c[maxDigit];
int i, carry, tmp;
carry = tmp = 0;
/**< 先以字符串形式读入数字 */
scanf("%s", a);
/**< 将字符串形式的数字转化为数组b储存 */
for(i=0; a[i]!='\0'; i++)
{
b[i] = a[i] - '0';
len++;
}
/**< 将数组b乘以2,存入新数组c */
for( i=len-1; i>=0; i-- )
{
tmp = b[i]*2+carry;
c[i] = tmp%10;
carry = tmp/10;
}
c[len] = carry;
/**< 对比结果 */
if(carry)
{
isFun = false;
}
for(i=0; i<=9; i++)
{
if(timesOfNum(b, len, i) != timesOfNum(c, len, i))
{
isFun = false;
// printf("checking num:%d\n", i);
// printf("b:%d\tc:%d\n", timesOfNum(b, len, i), timesOfNum(c, len, i));
}
}
/**< 输出部分 */
if(isFun)
printf("Yes\n");
else
printf("No\n");
if(carry)
printf("%d", c[len]);
for(i=0; i<len; i++)
{
printf("%d", c[i]);
}
system("pause");
}
/**< 统计数字n在数组a里出现的次数 */
int timesOfNum(int a[], int len, int n)
{
int i, cnt;
cnt = 0;
for(i=0; i<len; i++)
{
if(a[i] == n)
cnt++;
}
return cnt;
}