SOJ.Hex to Int

本文介绍了一个将十六进制字符串转换为十进制整数的C++函数实现,并展示了如何通过抛出异常来处理非法输入的情况。该函数能够处理正负数,并考虑了补码表示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Hex to Int
 
   
   
 
时间限制:1秒    内存限制:256兆
题目描述

 Write a function that parses a hex number as a string into a decimal integer. The function is defined as follows.

 

int parseHex(const char * hexString)

 

For example, hexString "A5" is 165 (10*16+5=165). So, parseHex("A5") returns 165.

 

Your implementation of parseHex function should throw a runtime_error exception if the binaryString is not a hex string.

 

The main function is:

 

int main()

{

string s;

while (cin >> s) {

try {

cout << parseHex(s) << endl;

} catch (runtime_error &ex) {

cout << ex.what() << endl;

}

}

return 0;

}

样例输入
10

fffffffF

9G3
样例输出
16

-1

Hex number format error
提示

You also NEED to submit the main() function.

The hex numbers mentioned above must be considered astwo's complements of 32-bit numbers. (ffffffff)16, therefore, is less than 0, since its most significant bit is 1.

 
   
   
 
提交





#include
   
    
#include
    
     
#include 
     
      
#include
      
       
using namespace std;
int parseHex(const char * const hexString)
{
int result=0; //...
	int len = strlen(hexString);
	int dec = 0;
	for(int i=0; i
       
        ='0' && hexString[i]<='9')||(hexString[i]>='A' && hexString[i]<='F')||(hexString[i]>='a' && hexString[i]<='f'))
		{
		if(hexString[i]>='0' && hexString[i]<='9') dec=hexString[i]-'0';
		else if(hexString[i]>='A' && hexString[i]<='F') dec=hexString[i]-'A'+10;
		else if(hexString[i]>='a' && hexString[i]<='f') dec=hexString[i]-'a'+10;
		result=16*result+dec; 
		}
		else throw runtime_error("Hex number format error");
	}
return result;
}
int main()
{
string s;
while (cin>>s) {
try {
cout << parseHex(s.c_str()) << endl;
} catch (runtime_error &ex) {
cout << ex.what() << endl;
}
}
return 0;
} 

       
      
     
    
   

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值