欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

自测-4 Have Fun with Numbers (20分)

程序员文章站 2022-06-07 14:15:26
...

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.

自测-4 Have Fun with Numbers (20分)
题意:输入一串数字,然后*2,看是否和原来的数构成的数字是否相同。

/*思路:1.由于位数大了过后,long int不能存储这么多的位数
        所以要手动模拟乘法,从最后一位进位上来,
        2.判断double后每个数字的出现次数与原始的数字的次数是都相同
        就用origin数组和check数组分别记录原始和*2后的每个数字的次数
        即set的方法*/
#include <stdio.h>
int main(){
    char digit[21];
    gets(digit);
    int check[10];   //存放double后的每个数的出现次数
    int origin[10];  //存放原始的每个数的出现次数
    int doublenum[21];//存档*2后的数
    memset(check,0,sizeof(check));
    memset(origin,0,sizeof(origin));
    int i,flag = 0;
    for(i=0;i<strlen(digit);i++){
        origin[digit[i] - '0']++;
    }
    for(i=strlen(digit)-1;i>=0;i--){
        doublenum[i] = (2*(digit[i]-'0')+flag)%10;
        check[(2*(digit[i]-'0')+flag)%10]++;
        if(2*(digit[i]-'0')/10==1){
            flag = 1;
        }else{
            flag = 0;
        }
    }
    if(flag==1){   //若直接位数都不一样多直接No
        printf("No\n");
        printf("1"); //进上来的1
        for(i=0;i<strlen(digit);i++){
            printf("%d",doublenum[i]);
        }
    }else{
        int f = 0;  //标志位,判断是否有出现次数不同的数。
        for(i=0;i<10;i++){
            if(origin[i]!=check[i]){
                f = 1;
                break;
            }
        }
        if(f==0){
            printf("Yes\n");
            for(i=0;i<strlen(digit);i++){
                printf("%d",doublenum[i]);
            }
        }else{
            printf("No\n");
            for(i=0;i<strlen(digit);i++){
                printf("%d",doublenum[i]);
            }
        }
    }
}
相关标签: PTA练习题