share my C++ solution


  • 0
    N
    class Solution {
    public:
        int reverse(int x) {
            long long ret = 0;
            int u = 1;
            if (x < 0) {
                u = -1;
                x = -x;
            }
            while (x != 0){
                ret = ret * 10 + x % 10;
                x /= 10;
            }
            ret = u * ret;
            if (ret > INT_MAX || ret < INT_MIN) ret = 0;
            return ret;
        }
    };
    

    some code is redundant

    new version:

    class Solution {
    public:
        int reverse(int x) {
            long long ret = 0;
            while (x != 0){
                ret = ret * 10 + x % 10;
                x /= 10;
            }
            if (ret > INT_MAX || ret < INT_MIN) ret = 0;
            return ret;
        }
    };
    

  • 0
    M

    @Netario36 Excuse me,I am a beginner here.May I ask a question?
    What if the variable 'x' is bigger than INT_MAX?
    My code went wrong when x=1293847564 because of overflow,and I have no ideal how to deal with it?
    So would you mind do me a favor?
    Thank you very much!


  • 0
    N

    @Moonfair x is an integer, but the value of reverse(x) may exceed integer limits.
    As in your case, x=1293847564 which is an integer, but reverse(x) = 4657483921 > INT_MAX(2147483647).
    You can use long long to store the result and check if the result is a valid integer in the end.


  • 0
    M

    @Netario36 Thank you very much!I tried as you told me,it passed.
    But this time it went wrong when the value is -2147483648.
    And I looked up the range of int,it's just on the edge.
    Is this the reason why it went wrong?If it is,could you please give me some advice?
    Thank you!


  • 0
    N

    @Moonfair My bad. I found some code in my original post is redundant and may cause some problems. I have posted a new version. Actually, there is no need to convert a number from negative into positive.
    In your case, x = -2147483648, x is an integer, but -x may exceed integer limits. If you try to convert x from negative into positive. It would lead to an unexpected answer.

    If the problem still persists, you can post your code here. I can help you figure out what went wrong.


  • 0
    M

    @Netario36 Amazing!I ignored that -x may be over the edge!
    It was accepted this time.
    Thank you!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.