3

I'm solving the problem of reversing an integer and got the error as below :

Line 8: Char 20: runtime error: signed integer overflow: 964632435 * 10 cannot be represented in type 'int' (solution.cpp)

My code is :

public:
    int reverse(int x) {
        int last=x%10;
        int rev=0;
        while(x){
            last=x%10;
            rev=rev*10+last;
            x=x/10;
        }
        return rev;
    }
};

I don't know why I'm getting this error. I'm a newbie to programming. I am not able to get the concept. Please someone explain it to me and how can I proceed further.

1 Answer 1

1

I get the answer. Actually there is integer overflow when we have rev approaching INT_MAX. We check beforehand whether or this statement would cause an overflow or not. Actually i found the below solution on internet and it worked

 int reverse(int x) {
        int last=x%10;
        int rev=0;
        while(x!=0){
            last=x%10;
            if (rev>=INT_MAX/10){
                if (rev>INT_MAX/10){
                    return 0;
                }else{
                    if (last>7){
                      return 0;
                    }
                }
            }
            if (rev<=INT_MIN/10){
                if (rev<INT_MIN/10){
                    return 0;
                }else{
                    if (last<-8){
                        return 0;
                    }
                }
            }
            rev=rev*10+last;
            x=x/10;
        }
        return rev;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.