十六进制转十进制

来源:互联网 发布:淘宝店铺线下推广方案 编辑:程序博客网 时间:2024/05/18 20:09

//牛客编程题:十六进制转十进制(多组输入),例如:输入 0xA,输出 10

/*分两步,1)判断标识符“0x”,如果本身输出不合法,无需做转化,2)按

输入十六进制从后往前(低位到高位)依次判断每个字符代表的数值大小,再

乘以16的位数的几次方(相当于十进制,百位千位对应于10的二次和三次方)

直到“0x”处停止,累加输出对应的十进制数*/


#include <iostream>
#include <vector>
#include <string>

#include <math.h>



using namespace std;


int AlpToDec(char c)
{//十六进制需要特殊转化的字符
if (c == 'a' || c == 'A'){
return 10;
}
if (c == 'b' || c == 'B'){
return 11;
}
if (c == 'c' || c == 'C'){
return 12;
}
if (c == 'd' || c == 'D'){
return 13;
}
if (c == 'e' || c == 'E'){
return 14;
}
if (c == 'f' || c == 'F'){
return 15;
}
return -1;
}


int HexToDec(string hex)
{

//异常情况
if (hex.length() < 3){
return -1;
}
if (hex[0] != '0' || hex[1] != 'x'){
return -1;
}

//从后往前,依次转化值,累加输出
int sum = 0, bit = 0;
for (int i = hex.length() - 1; i > 1; --i){
if (hex[i] - '0' >=0 && hex[i] - '0'<= 9){
sum += (hex[i] - '0')*pow(16, bit);
bit++;
}
else if (AlpToDec(hex[i])){
sum += AlpToDec(hex[i])*pow(16, bit);
bit++;
}
else{
return -1;
}
}
return sum;


}


int main(int argc, char **argv)
{
vector<string> hexs;
string hex;
while (cin >> hex)
{
hexs.push_back(hex);
}
for (vector<string>::iterator it = hexs.begin(); it != hexs.end(); it++){
int dec = HexToDec(*it);
if (dec < 0){
cout << "error hex num!!" << endl;

else{
cout << dec << endl;
}
}
return 0;
}