算法练习Day9

96 阅读1分钟

题目描述

写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。

数据范围:保证结果在 1≤n≤2^31−1

题目来源

题目来源(www.nowcoder.com/practice/8f…)

输入描述

输入一个十六进制的数值字符串

输出描述:

输出该数值的十进制字符串。不同组的测试用例用\n隔开。

输入:
0xAA
输出:
170

思路

这道题从前往后遍历即可,注意分一下字母和数字,注意前两位是0x跳过即可。

具体实现

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<iostream>
#include<math.h>
using namespace std;
​
int main() {
    string str;
    while (getline(cin, str)) {
        int i = str.length();
        int m = 0;
        for (int j = 2; j < i; j++) {
            if (toupper(str[j]) >= 'A') {
                m += (toupper(str[j]) - 'A' + 10) * (pow(16, (i - j - 1)));
            } else
                m += (str[j] - '0') * (pow(16, (i - j - 1)));
        }
        printf("%d\n", m);
    }
    return 0;
}

时间复杂度

时间复杂度为O(n)

小结

写的过程中有两点需要注意,用toupper将所有字母字符处理成大写更方便一些

还有就是字符串的数字也是字符,不等于他自身表示的数字,也需要处理

新学了次方函数pow,头文件是math.h