15.1 Reverse Integer(cpp): have not check integer overflow....
micfan opened this issue · 7 comments
micfan commented
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
yeah?
soulmachine commented
Thanks for pointing this out, I'll check it later.
billlipeng commented
signed long long int r=0;
for(;x;x/=10)
r = r*10+x%10;
if(abs(r)>(pow(2,31)-1)) return 0;
else return (int) r;
micfan commented
@billlipeng
Thanks!
https://oj.leetcode.com/problems/reverse-integer/
#include <math>
class Solution {
public:
int reverse(int x) {
signed long long int result = 0;
for (; x; x/=10)
{
result = result * 10 + x % 10;
}
if (abs(result) > (pow(2, 31)-1)) {
return 0;
} else {
return result;
}
}
};
kingFighter commented
+1. The solution is wrong.
soulmachine commented
谢谢,我周末抽时间检查一下
billlipeng commented
This issue was solved. Plz check my comment on Feb 26, update the code and close it. Thanks a lot!
idear1203 commented