题解 | #进制转换2#

进制转换2

https://www.nowcoder.com/practice/ae4b3c4a968745618d65b866002bbd32


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

int getNum(char ch) {
    if ('0' <= ch && ch <= '9') {
        return (int)(ch - '0');
    }
    else if ('A' <= ch && ch <= 'Z') {
        return (int)(ch - 'A' + 10);
    }
    else {
        return (int)(ch - 'a' + 36);
    }
}
char getChar(int num) {
    if (0 <= num && num <= 9) {
        return (char)(num + '0');
    }
    else if (10 <= num && num <= 35) {
        return (char)(num + 'A' - 10);
    }
    else {
        return (char)(num + 'a' - 36);
    }
}

int main()
{
    int M, N;
    char X[100];   //
    scanf("%d %d", &M, &N);
    scanf("%s", X); // X是M进制,可能包含字母,比如十六进制,14d4
    int len = strlen(X);
    int X_index = 0;
    int new_X[100]; // 目标进制存储
    int new_X_index = 0;
    while (X_index < len) {
        int yushu = 0;
        // 模拟除法
        for (int i = X_index; i < len; i++) {
            int temp = yushu * M + getNum(X[i]);  // 以10进制作为中转进制
            X[i] = getChar(temp / N);
            yushu = temp % N;
        }
        new_X[new_X_index++] = getChar(yushu);
        // 前面是0的跳过
        for (int i = X_index; ; i++) {
            if (X[i] != '0' || i > len) {
                X_index = i;
                break;
            }
        }
    }
    // 打印目标进制
    for (int i = new_X_index - 1; i >= 0; i--)
    {
        printf("%c", new_X[i]);
    }
    printf("\n");
}


全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 12:04
毕业生招你惹你了,问一个发薪日来一句别看网上乱七八糟的你看哪个工作没有固定发薪日扭头就取消了面试就问了一句公司都是这个态度吗还搞上人身攻击了...
程序员小白条:呃呃呃,都还没面试,我都不会问这么细,何况通不通过,去不去都另说,你没实力和学历的话,在外面就这样,说实话没直接已读不回就不错了,浪费时间基本上
点赞 评论 收藏
分享
下北澤大天使:你是我见过最美的牛客女孩😍
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务