[英]Integer overflow and std::stoi
如果 x > INT_MAX 或如果 x > INT_MIN 函数将返回 0... 或者这就是我想要做的 :)
在我的测试用例中,我传入一个值为 INT_MAX + 1... 2147483648 ... 以引入整数溢出以查看程序如何处理它。
我单步执行...我的 IDE 调试器说该值在溢出时立即变为 -2147483648,并且出于某种原因,程序执行超出了这两个语句:
如果 (x > INT_MAX) 如果 (x < INT_MIN)
并保持崩溃 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;
}
任何类似(x > INT_MAX)
且x
为int
类型的测试都不会评估为真,因为x
的值不能超过INT_MAX
。
无论如何,即使2147483647
是有效范围,其反向7463847412
是。 因此,我认为它能够更好地让stoi
“试一试”的价值观和“catch”任何转换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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.