【华为机试练习】进制转换

题目描述
写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。(多组同时输入 )
输入描述:
输入一个十六进制的数值字符串。
输出描述:
输出该数值的十进制字符串。


解法(C语言版):

#include<stdio.h>
#include<math.h>

int hex2dec(char hex)
{
    if(hex >= '0' && hex <= '9')
        return hex - '0';
    else if(hex >= 'A' && hex <= 'F')
        return hex - 55;
    else
        return -1;
}

char *dec2str(int dec)
{
    int i, j;
    char str[100] = {0};
    char restr[100] = {0};
    i = 0;
    do
    {
        restr[i++] = dec % 10 + '0';
        dec /= 10;
    }while(dec);
    j = 0;
    i = i - 1;
    while(i >= 0)
        str[j++] = restr[i--];
    return str;
}

int main()
{
    char instr[100] = {0};
    int len, dec, tmp, i, j;
    while(gets(instr))
    {
        dec = 0;
        len = strlen(instr);
        for(i = len - 1, j = 0; i > 1; --i, ++j)
        {
            tmp = hex2dec(instr[i]);
            dec += tmp * pow(16, j);
        }
        printf("%s\n", dec2str(dec));
        memset(instr, 0, 100);
    }
    return 0;
}

猜你喜欢

转载自blog.51cto.com/13614527/2467306