c++-进制转换

来源:互联网 发布:understand mac注册码 编辑:程序博客网 时间:2024/06/04 20:30

题目描述

写出一个程序,接受一个十六进制的数值字符串,输出该数值的十进制字符串。

输入描述:

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

输出描述:

输出该数值的十进制字符串。

示例1

输入

0xA

输出

10

解法:

#include <iostream>#include <cmath>using std::cin;using std::cout;using std::endl;using std::string;int solution(string res){    int len=res.size();    int sum=0;    int a;    for(auto c : res){        if(c>='a' && c<='z')            a=c-'a'+10;        else if(c>='A' && c<='Z')            a=c-'A'+10;        else            a=c-'0';        if(len<=res.size()-2)        sum=sum+a*pow(16,len-1);        len--;    }    return sum;    }int main(){    string res;    while(cin>>res){        cout<<solution(res)<<endl;    }    return 0;}



原创粉丝点击