美文网首页LeetCode
两个七进制数相加 七进制输出

两个七进制数相加 七进制输出

作者: dopami | 来源:发表于2018-07-15 11:25 被阅读377次

    #include#include#include

    //进制转换

    int hex2int(char *str, int *result){

        *result = 0;

        while(*str > 0)

    {

    // printf("\nstr %s\n",str);

    // printf("*str %c\n",*str);

    // printf("==========\n");

            if(*str >= '0' && *str <= '6')

    {

    //printf("*str %c\n",*str);

                *result = *result * 7 + *str++ - '0';

    //printf("*result %d\n",*result);

            }

    else if(*str >= 'a' && *str <= 'f')

    {

                *result = *result * 16 + *str++ - 'a' + 10;

            }

    else if(*str >= 'A' && *str <= 'F')

    {

                *result = *result * 16 + *str++ - 'A' + 10;

            }

    else

    {

                return 1;

            }

        }

    //printf("*result %d\n",*result);

        return 0;

    }

    int int2num(int num, char **result, char scale){

        char arr[32];

        char *temp = arr + 32;

        //char *table = "0123456789abcdef";

    char *table = "0123456";

        *--temp = 0;

        while(num > scale)

    {

            *--temp = table[num % scale];

            num = num / scale;

        }

        if(num)

    {

            *--temp = table[num];

        }

    else if(*temp == 0)

    {

            *--temp = '0';

        }

    // printf("\ntemp %s\n",temp);

        *result = strdup(temp);

    }

    char* ADD(char *x, char *y){

        int a, b;

        if(hex2int(x, &a)){

            printf("x isn't hex.\n");

        }

        if(hex2int(y, &b)){

            printf("y isn't hex.\n");

        }

        int2num(a + b , &x, 7);

        return x;

    }

    int main(){

        char x[32], y[32];

        printf("x: ");

        scanf("%s", x);

        printf("y: ");

        scanf("%s", y);

        char *t = ADD(x, y);

        printf("x + y = %s\n", t);

        free(t);//释放内存

        return 0;

    }

    相关文章

      网友评论

        本文标题:两个七进制数相加 七进制输出

        本文链接:https://www.haomeiwen.com/subject/qkcppftx.html