如果x> INT_MAX或x> INT_MIN,该函数将返回0 ...或这就是我正在尝试做的事情:)
在我的测试用例中,我传入的是INT_MAX +1 ... 2147483648 ...的值,以引入整数溢出来查看程序如何处理它。
我逐步完成...我的IDE调试器说,溢出后该值立即变为-2147483648,并且由于某种原因,程序将执行以下两个语句之外的操作:
如果(x> INT_MAX)
如果(x 并保持崩溃int revInt = std :: stoi(strNum);
说超出范围 一定很简单,但这让我感到困惑。给定x> INT_MAX,为什么程序在返回该std :: stoi()之前不返回?任何帮助表示赞赏。谢谢!功能和测试平台的完整列表如下:(对不起,代码插入格式设置有误。) 主要:#include <iostream>
#include <algorithm>
#include <string> //using namespace std;
class Solution {
public: int reverse(int x)
{
// check special cases for int and set flags:
// is x > max int, need to return 0 now
if(x > INT_MAX)
return 0;
// is x < min int, need to return 0 now
if(x < INT_MIN)
return 0;
// is x < 0, need negative sign handled at end
// does x end with 0, need to not start new int with 0 if it's ploy numeric and the functions used handle that for us
// do conversion, reversal, output:
// convert int to string
std::string strNum = std::to_string(x);
// reverse string
std::reverse(strNum.begin(), strNum.end());
// convert reversed string to int
int revInt = std::stoi(strNum);
// multiply by -1 if x was negative
if (x < 0)
revInt = revInt * -1;
// output reversed integer
return revInt;
}
};
#include <iostream>
int main(int argc, const char * argv[]) {
// test cases
// instance Solution and call it's method
Solution sol;
int answer = sol.reverse(0); // 0
std::cout << "in " << 0 << ", out " << answer << "\n";
answer = sol.reverse(-1); // -1
std::cout << "in " << -1 << ", out " << answer << "\n";
answer = sol.reverse(10); // 1
std::cout << "in " << 10 << ", out " << answer << "\n";
answer = sol.reverse(12); // 21
std::cout << "in " << 12 << ", out " << answer << "\n";
answer = sol.reverse(100); // 1
std::cout << "in " << 100 << ", out " << answer << "\n";
answer = sol.reverse(123); // 321
std::cout << "in " << 123 << ", out " << answer << "\n";
answer = sol.reverse(-123); // -321
std::cout << "in " << -123 << ", out " << answer << "\n";
answer = sol.reverse(1024); // 4201
std::cout << "in " << 1024 << ", out " << answer << "\n";
answer = sol.reverse(-1024); // -4201
std::cout << "in " << -1024 << ", out " << answer << "\n";
answer = sol.reverse(2147483648); // 0
std::cout << "in " << 2147483648 << ", out " << answer << "\n";
answer = sol.reverse(-2147483648); // 0
std::cout << "in " << -2147483648 << ", out " << answer << "\n";
return 0;
}
答案 0 :(得分:4)
由于(x > INT_MAX)
的值不能超过x
,因此int
类型为x
的任何测试(如INT_MAX
都将永远不会为真。
无论如何,即使2147483647
是有效范围,其反向7463847412
也不是。
因此,我认为最好让stoi
“尝试”转换值并“捕获”任何out_of_range
-exception`。以下代码说明了这种方法:
int convert() {
const char* num = "12345678890123424542";
try {
int x = std::stoi(num);
return x;
} catch (std::out_of_range &e) {
cout << "invalid." << endl;
return 0;
}
}