题解 | #数制转换#

数制转换

https://www.nowcoder.com/practice/8ef02ef8571b417d8c311a87861f7a03

#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#define MAXSIZE 200
typedef int ElemType;
// 计算字符串长度:
int Length(char a[]) {
    int n = 0;
    for (int i = 0; a[i] != '\0'; i++) {
        n++;
    }
    return n;
}
typedef struct {
    ElemType data[MAXSIZE];
    int top;
} Stack_int;
// 初始化一个数字栈:
void InitStack(Stack_int* S) {
    S->top = -1;
}
// 进栈:
bool Push(Stack_int* S, ElemType x) {
    if (S->top == MAXSIZE - 1)
        return false;
    else {
        S->data[++S->top] = x;
        return true;
    }
}
// 出栈:
bool Pop(Stack_int* S, ElemType* x) {
    if (S->top != -1) {
        *x = S->data[S->top--];
        return true;
    } else
        return false;
}
int main() {
    int a, b;
    char c[10] = "";
    scanf("%d %s %d", &a, c, &b);
    int len = Length(c);
    long n = 0;
    int k = 0;
    for (int i = len - 1; i >= 0; i--) {
        if (c[i] >= 'a' && c[i] <= 'f') {
            int num = c[i] - 'a' + 10;
            n += num * pow(a, k);
            k++;
        } else if (c[i] >= 'A' && c[i] <= 'F') {
            int num = c[i] - 'A' + 10;
            n += num * pow(a, k);
            k++;
        } else {
            int num = c[i] - '0';
            n += num * pow(a, k);
            k++;
        }
    }
    Stack_int S;
    InitStack(&S);
    while (n != 0) {
        int x = n % b;
        n /= b;
        Push(&S, x);
    }
    while (S.top != -1) {
        int y;
        Pop(&S, &y);
        if (y >= 10)
            printf("%c", 'A' + (y - 10));
        else
            printf("%c", '0' + y);
    }
    printf("\n");
    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务