由于实例超出范围异常,一直试图解决运行时错误。我将int转换为字符串,将字符串反转并使用stoi将其返回给int。简单的测试数字可以完美地反转,但是更大的数字超出范围。不确定代码中的何处要针对超出范围的异常进行调整。超级卡住了,请帮忙。
int reverse(int x) {
bool negflag = false;
if(x < 0)
{
negflag = true;
}
string xString = std::to_string(abs(x));
std::reverse(xString.begin(),xString.end());
int xNum = std::stoi(xString);
return (negflag == true)? -xNum: xNum;
}
这是返回的错误:
terminate called after throwing an instance of 'std::out_of_range'
what(): stoi
Last executed input: 1534236469
较小的数字效果很好。
Your input: 123
Output: 321
Expected: 321
我的字符串末尾是否有\\ 0,导致转换中的所有内容丢失?这些C ++方法的新手。非常感谢。真的很想确定这些方法并能够轻松使用它们。
重要信息:
Note: Assume we are dealing with an environment which could only store
integers within the 32-bit signed integer range:
[-2 31 到+2 31 -1]
For the purpose of this problem,assume that your function returns 0 when
the reversed integer overflows.
->> 不确定如何制定将返回0的if语句;超过32位时。