题解 | #纯C,不使用库函数#

进制转换2

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

//基本思路:m进制转10进制再转n进制
#include <stdio.h>

char list[36] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };

int len(char* s) {
    int i = 0;
    while (s[i] != '\0') i++;
    return i;
}

int change(char c) {
    if (c >= '0' && c <= '9') return c - '0';
    if (c >= 'A' && c <= 'Z') return c - 'A' + 10;
    return -1;
}

long long to_dec(char* xm, int m) {
    char xd[50] = { '\0' };
    long long base = 1, dec = 0;
    for (int i = len(xm) - 1; i >= 0; i--) {
        dec += change(xm[i]) * base;
        base *= m;
    }
    return dec;
}

void to_n(long long dec, int n, char* xn) {
    int i = 0;
    long long shang, r;
    while (dec) {
        r = dec % n;
        dec /= n;
        xn[i++] = list[r];
    }
}

int main() {
    int m, n;
    char xm[50], xn[50] = { '\0' };
    scanf("%d%d%s", &m, &n, &xm);
    long long dec = to_dec(xm, m);
    to_n(dec, n, xn);
    for (int i = len(xn) - 1; i >= 0; i--) printf("%c", xn[i]);

    return 0;
}

本题数据范围比较小,如果位数很长则应该用高精度算法计算十进制数

全部评论

相关推荐

去B座二楼砸水泥地:不过也可以理解,这种应该没参加过秋招
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务