Huawei Written Test Questions: Hex Conversion

Title description

Write a program that accepts a hexadecimal number and outputs the decimal representation of the value. (Multiple groups input at the same time)

Enter description:

Enter a hexadecimal numeric string.

Output description:

Output the decimal string of this value.

Example 1

Input

0xA

Output

10
#include <iostream>
#include <string>
#include <map>
#include <cmath>

using namespace std;

map<char, int> m = {{'A', 10},
                    {'B', 11},
                    {'C', 12},
                    {'D', 13},
                    {'E', 14},
                    {'F', 15}};

int convert(string s) {
    string str = "";
    int len = s.length();
    int result = 0;
    for (int i = len - 1; i >= 2; --i) {
        if (isdigit(s[i])) {
            result += (s[i] - '0') * pow(16, len - 1 - i);
        } else {
            result += m[s[i]] * pow(16, len - 1 - i);
        }
    }
    return result;
}

int main() {
    string s;
    while (cin >> s) {
        cout << convert(s) << endl;
    }
    return 0;
}

 

Published 34 original articles · Like 10 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/weixin_41111088/article/details/104770543