soulmachine / leetcode

LeetCode题解,151道题完整版。
BSD 3-Clause "New" or "Revised" License
11.27k stars 3.43k forks source link

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

Open micfan opened 9 years ago

micfan commented 9 years ago

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 9 years ago

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

billlipeng commented 9 years ago
 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 9 years ago

@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 9 years ago

+1. The solution is wrong.

soulmachine commented 9 years ago

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

billlipeng commented 9 years ago

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

idear1203 commented 9 years ago

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