【杂题】进制转换

Prob

社团的一道水题。

Input

共三行,第一行是一个正整数,表示需要转换的数的进制n(2≤n≤16),第二行是一个n进制数,若n>10则用大写字母A-F表示数码10-15,并且该n进制数对应的十进制的值不超过1000000000,第三行也是一个正整数,表示转换之后的数的进制m(2≤m≤16)。

Output

一个正整数,表示转换之后的m进制数。

Code

#include <cstdio>
#include <cstring>
using namespace std;

const int N = 32;
const char digit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
const int weight[] = {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};

int n, tosn;

inline int numize(const char &ch){
    if('A' <= ch && ch <= 'Z')return ch - 'A' + 10;
    else return ch - 48;
}

struct num{
    int d[N];   // 倒序存储不压位
    int len;
    inline void read(const int &sn){
        // system of numeration
        memset(d, 0, sizeof(d));
        char x[N];
        scanf("%s", x + 1);
        len = strlen(x) - 1;
        for(int i = 1; i <= len; ++i)d[i] = numize(x[len - i + 1]);
    }
    inline void println(){
        for(int i = len; i >= 1; --i)printf("%c", digit[d[i]]);
        printf("\n");
    }
    inline void conv(const int &tosn){
        int t = 0;
        for(int i = len; i >= 1; --i)t = t * n + d[i];
        int x[N], cur = 0;
        memset(x, 0, sizeof(x));
        while(t){
            x[++cur] = t % tosn;
            t /= tosn;
        }
        len = cur;
        for(int i = 1; i <= len; ++i)d[i] = x[i];
    }
}inp;

int main(int argc, char const *argv[]){
    scanf("%d", &n);
    inp.read(n);
    scanf("%d", &tosn);
    inp.conv(tosn);
    inp.println();
    return 0;
}

Review

  • 进制转换。代码有点工程向的意思了(bushi
  • 没有做太多优化,反正规模不大
posted @ 2021-09-26 13:48  Mojibake  阅读(84)  评论(0编辑  收藏  举报
知识共享许可协议
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。