数制转换 OpenJ_Bailian - 2710

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liuYinXinAll/article/details/82145265

题目要求

求任意两个不同进制非负整数的转换(2进制~16进制),所给整数在long所能表达的范围之内。
不同进制的表示符号为(0,1,…,9,a,b,…,f)或者(0,1,…,9,A,B,…,F)。

Input

输入只有一行,包含三个整数a,n,b。a表示其后的n 是a进制整数,b表示欲将a进制整数n转换成b进制整数。
a,b是十进制整数,2 =< a,b <= 16。

Output

输出包含一行,该行有一个整数为转换后的b进制数。输出时字母符号全部用大写表示,即(0,1,…,9,A,B,…,F)。

Sample Input

15 Aab3 7

Sample Output

210306

总结

题的思路是很简单的,主要是遇到几个问题
1. 变量一定要初始化再使用,在本地调试一直没问题,但是支持是Runtime Error, 后来发现有个变量没有初始化
2. ctype.h 库使用,提供 isdigit 和 toupper() 函数,可以少些很多代码
3. 交换数组时候,可以用双指针,终止条件是 i >= j;

代码如下

#include <stdio.h>
#include <ctype.h>

#define debug(x) printf("%d\n", x)
const int N = 1000;
char out[N];


int main() {

    char c;
    int from, to,bit,mod, len = 0, swp;
    long long num = 0;
    scanf("%d", &from);
    scanf("%c", &c); // 出去空格 
    while(scanf("%c", &c) && c != ' '){
        if ( isdigit(c)) 
            bit =  c - '0';
        else {
            bit = toupper(c) - 'A' + 10;
        }
        num = num * from + bit;
    }
    scanf("%d", &to);
    if (num == 0) {
        printf("0");
        return 0;
    };
    while (num != 0){
        mod = num % to;
        num = num / to;
        out[len++]  = (mod >= 10 ? 'A' - 10: '0') + mod;  
    }
    out[len] = '\0';
    for (int i =0, j = len-1; i <j; ++i, --j){
        swp = out[i];
        out[i] = out[j];
        out[j] = swp;
    }
    printf("%s\n", out);
    return 0;
} 

猜你喜欢

转载自blog.csdn.net/liuYinXinAll/article/details/82145265