c++-进制转换

题目描述

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

输入描述:

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

输出描述:

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

示例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;
}



posted on 2017-12-14 18:58  sichenzhao  阅读(122)  评论(0编辑  收藏  举报

导航