Day9十六进制转换为十进制

124 阅读1分钟

描述

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

输入描述:

1n23111\le n \le 2^{31}-1

输出描述:

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

示例

输入:
0xAA
输出:
170

具体思路

(1)原理:整数运算一样,小数部分换成16即可 (2)具体方法步骤如下:

0XAA=A161+A1600XAA = A*16^{1}+A*16^{0}

img

具体实现

#include <math.h>
#include <algorithm>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <stdlib.h>
#include <cstdlib>
#include <cstring>//#include "./include/list/sqlist.h"
​
using namespace std;
​
//字母转换为Int类型字符
int StringToInt(char c){
    if(c >= 'A' && c <= 'F') return c - 55;//'A'到'F'转换为十进制的10到15
    else return c - 48;//'0'到'9'转换为十进制的0到9
}
​
//求解对应的平方数
/**
 * @description: 
 * @param {int} num
 * @return {*}
 */
int Power(int num){
    int ans = 1;
    if(num == 0) return 1;
    for(int i = num; i > 0; i--){
        ans *= 16;
    }
    return ans;
}
​
//day9
//十六进制转换为10进制输出
//法1:暴力破解法,位权相加法,十六进制数除于十六,然后直接输出
int HexadecimalToDecimal(string s){
    //首先将十六进制的数进行辗转相除操作
    //直接遍历,除了前两位,都将数字成宇16的次方的位数
    int len_s = s.length();//除去前面0x数字的位数
    int ans;
    if(len_s == 0) return 0;
    //进行运算过程
    for(int i = len_s - 1, k = 0; i >= 2; i--, k++){
        int temp = StringToInt(s[i]);
        ans += temp * Power(k);
    }
    return ans;
}
​
int main(){
​
​
    // //day06
    // LinkList L;
    // int n;//输入数据数量
    // int index = 0;//输入的位置
    // ListNode* p;
    // while(scanf("%d",&n) != EOF){
    //     L = ListTailInsert(L,n);
    //     scanf("%d",&index);
    //     if(index == 0) std::cout << 0 << std::endl;
    //     else{
    //         p = FindKInListIII(L,index);
    //         if(p != NULL) printf("%d\n",p->data);
    //     }
    //     //PrintLinkedList(L);
    // }
    // int month_;
    // while(scanf("%d",&month_) != EOF){
    //     int ans = GetRabbitNums(month_);
    //     printf("%d\n",ans);
    // }
    //day8
    string s;
    while( cin >> s){
        int ans = HexadecimalToDecimal(s);
        printf("%d\n",ans);
    }
    //SplitStringIII(s);
    system("pause");
    return 0;
}

image.png

复杂度

时间复杂度:O(n)+O(1)

小结

充分了解进制之间是如何进行转换的 进制转换