sarosh mirza
sarosh mirza

Reputation: 702

detecting 32 bit integer overflow

I have a simple method that basically reverses the signed integer. This function works till the integer is under or equal to 32 bit. for example :-

input = 321
output = 123

input = -321
output = -123

input = 1534236469
output = 9646324351    //this value is wrong. 

expected output = 0

I want to detect the integer overflow and return 0 in that case. Below is the code for the function

    int reverse(int x) {
    int number = x;
    bool negative = false;
    if(number<0){
        negative = true;
        number *= -1;
    }

    int reversed = 0;
    while (number != 0){
        int reminder = number % 10;
        reversed = (reversed * 10) + reminder;
        number /= 10;
    }
    if(negative){
        reversed *= -1;
    }
    return reversed;
}

Furthermore, if I change the input and output into signed long I get the required output but I want to detect the integer overflow and return 0.

Upvotes: 3

Views: 5261

Answers (2)

Matt Timmermans
Matt Timmermans

Reputation: 59303

Before you multiply reversed by 10, just check to make sure it's small enough to multiply by 10.

Similarly, before you add remainder, check to make sure it's small enough to add remainder.

There's a clever trick you can use for the addition, but at your level you probably shouldn't:

if ((reversed += remainder) < remainder) {
    //overflow
}

Note that the trick only works if both reversed and remainder are unsigned.

Upvotes: 2

Mike Nakis
Mike Nakis

Reputation: 62064

This hint might help you complete your assignment:

You are only going to get integer overflow if your final number is 10 digits long and the first digit ends up being above or equal to 2.

Which means that you are going to get integer overflow if your original number is also 10 digits long and the last digit is 2 or above.

Upvotes: 2

Related Questions