Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
micfan opened this issue Jan 12, 2015 · 7 comments
Open

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

micfan opened this issue Jan 12, 2015 · 7 comments

Comments

@micfan
Copy link

micfan commented Jan 12, 2015

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
Copy link
Owner

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

@billlipeng
Copy link

 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
Copy link
Author

micfan commented Feb 27, 2015

@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
Copy link

+1. The solution is wrong.

@soulmachine
Copy link
Owner

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

@billlipeng
Copy link

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

@idear1203
Copy link
Contributor

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants