题解 | #进制转换#
进制转换
http://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6
#include <iostream>
#include <string>
using namespace std;
/*
思路:
十六进制转化10进制,根据ASCII的字符位置进行相减操作'B'-'A' + 10 =1, ‘7’-‘0’=7,获取的结果deciOut=deciOut*16+temp
*/
int HexToDeci(string strIn)
{
int deciOut = 0;
if(strIn.length() == 0) {
return 0;
}
int pos = strIn.find('x');
int len = strIn.length();
for(int i = pos+1; i < len; i++) {
int temp;
if(strIn[i] >= 'A' && strIn[i] <= 'F') {
temp = strIn[i] - 'A' + 10;
} else if (strIn[i] >= '0' && strIn[i] <= '9') {
temp = strIn[i] - '0';
}
deciOut = deciOut*16 + temp;
}
return deciOut;
}
int main()
{
string strIn;
while(cin>>strIn) {
cout<<HexToDeci(strIn)<<endl;
}
return 0;
}