soulmachine/leetcode

15.1 Reverse Integer(cpp): have not check integer overflow....

micfan opened this issue · 7 comments

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?

Thanks for pointing this out, I'll check it later.

 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;

@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;
        }
    }
};

+1. The solution is wrong.

谢谢,我周末抽时间检查一下

This issue was solved. Plz check my comment on Feb 26, update the code and close it. Thanks a lot!