进制转换(将M进制的数X转换为N进制的数输出)

来源:互联网 发布:苹果手机连不上数据 编辑:程序博客网 时间:2024/05/16 01:29

题目

题目描述:将M进制的数X转换为N进制的数输出。输入:输入的第一行包括两个整数:M和N(2<=M,N<=36)。下面的一行输入一个数X,X是M进制的数,现在要求你将M进制的数X转换成N进制的数输出。输出:输出X的N进制表示的数。样例输入:16 10F样例输出:15提示:输入时字母部分为大写,输出时为小写,并且有大数据。


思路

  • 大整数乘法转换成10进制数组
  • 大整数除法转换成指定进制数

AC代码

#include <stdio.h>#include <stdlib.h>#include <string.h> #define LEN 2000 char str[LEN], another[LEN];int  ten[LEN]; int switchToTen();void switchToAnother(int k, int n); int main(){    int m, n, k;     while (scanf("%d %d", &m, &n) != EOF) {        scanf("%s", str);                 k = switchToTen(m);         switchToAnother(k, n);      }     return 0;} int switchToTen(int m){    int i, j, len, k, c;     //初始化    len = strlen(str);    k = 1;    memset(ten, 0, sizeof(ten));     //转换为10进制数    for (i = 0; i < len; i ++) {        for (j = 0; j < k; j ++) {            ten[j] *= m;        }        if (str[i] >= '0' && str[i] <= '9') {            ten[0] += str[i] - '0';        }else if (str[i] >= 'A' && str[i] <= 'Z') {            ten[0] += str[i] - 'A' + 10;        }else if (str[i] >= 'a' && str[i] <= 'z') {            ten[0] += str[i] - 'a' + 10;        }         for (j = c = 0; j < k; j ++) {            ten[j] += c;                 if (ten[j] >= 10) {                c = ten[j] / 10;                ten[j] %= 10;               }else {                c = 0;            }        }         while (c) {            ten[k ++] = c % 10;            c /= 10;        }    }      //翻转数组    int temp;    for (i = 0, j = k - 1; i < j; i ++, j --) {        temp = ten[i];        ten[i] = ten[j];        ten[j] = temp;    }    return k;} void switchToAnother(int k, int n){    int sum, i, r, t, d;     sum = 1;    r = 0;    memset(another, 0, sizeof(another));     while (sum) {        sum = 0;         for (i = 0; i < k; i ++) {            d = ten[i] / n;            sum += d;             if (i == k - 1) {                t = ten[i] % n;                if (t >= 0 && t <= 9) {                    another[r] = t + '0';                }else {                    another[r] = t - 10 + 'a';                }                r ++;            }else {                ten[i + 1] += ten[i] % n * 10;            }             ten[i] = d;        }    }         //打印是输出    for (i = r - 1; i >= 0; i --) {        printf("%c", another[i]);    }    printf("\n");}/**************************************************************    Problem: 1080    User: wangzhengyi    Language: C    Result: Accepted    Time:170 ms    Memory:920 kb****************************************************************/