PAT Have Fun with Numbers 有几个测试点过不去

2020-02-22 23:56发布

问题:

这是PAT的一道题。
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

#include<stdio.h>
#include<string.h>

void doublenum(char*, char*);   //双倍
int compare(char*, char*);      //比较两组数

int main()
{
    char a[20], b[20] = {'\0'};
    int i;
    gets(a);
    doublenum(a, b);
    i = compare(a, b);
    if( i == 10 ) printf("Yes\n");
    else printf("No\n");

    puts(b);
    return 0;
}

void doublenum(char *a, char *b)
{
    int i , z;
     for( i=0; a[i]!='\0'; ++i){
        z = (a[i]-'0')*2;
        b[i] = z%10 + '0';
        if( i != 0 )
            b[i-1] += z/10;
    }
}
int compare(char *a, char *b)
{
    int i, z, c[10] = {0};          //创建一个数组里放0~9的个数
    for( i=0; a[i]!='\0'; ++i){         //第一组加个数
        for( z = 0; z<10; ++z)
            if( a[i]-48 == z ) c[z]++;
    }
    for( i=0; a[i]!='\0'; ++i){         //第二组减个数
        for( z = 0; z<10; ++z)
            if( b[i]-48 == z ) c[z]--;
    }
    for( i=0; i<10; ++i )           //如果结果都为0,i为10, 否则,i<10
        if( 0 != c[i] )
            break;
    return i;
}

第三个和最后俩测试点一直过不去。

回答1:

别的错先不看, 先看最直接的错误, 很显然, 当输入的长度为20的时候, 你就会出错, 因为在C语言中, 长度为20的字符串, 开char数组的话至少开21个, 还需要一个'\0', 所以长度为20的时候你就出错了

先将char a[20], b[20] = {'\0'}; 改成 char a[30], b[30] = {'\0'}; 再想有没有其他问题

另外, 建议你在做大整数的运算的时候, 不要从高位往低位计算, 这样进位容易出错, 在这道题, 只需要做Double, 所以不会有问题, 但是如果是加减法或者别的运算, 这个顺序就危险了