leetcode icon indicating copy to clipboard operation
leetcode copied to clipboard

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

Open micfan opened this issue 9 years ago • 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?

micfan avatar Jan 12 '15 15:01 micfan

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

soulmachine avatar Feb 09 '15 05:02 soulmachine

 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 avatar Feb 26 '15 21:02 billlipeng

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

micfan avatar Feb 27 '15 13:02 micfan

+1. The solution is wrong.

kingFighter avatar Jul 14 '15 05:07 kingFighter

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

soulmachine avatar Jul 14 '15 05:07 soulmachine

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

billlipeng avatar Aug 20 '15 21:08 billlipeng

同发现问题。我觉得这个解很好。 https://leetcode.com/discuss/51595/short-accepted-c-solution-using-int-without-long-or-string

idear1203 avatar Aug 25 '15 05:08 idear1203