Detecting 32-bit integer overflow

I have a simple method that basically changes a signed integer. This function works until the integer is 32 bits. eg: -

input = 321
output = 123

input = -321
output = -123

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

expected output = 0

      

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

    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;
}

      

Also, if I change the input and output to a signed long, I get the output I want, but I want to detect an integer overflow and return 0.

+3


source to share


2 answers


Before you multiply reversed

by 10, just check that it is small enough to multiply by 10.

Likewise, before adding remainder

, make sure it is small enough to add remainder

.

There's a clever trick there that you can use to add, but at your level you probably shouldn't:



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

      

Please note that the trick works only if both reversed

and remainder

are not a sign.

+3


source


This tip will help you complete your assignment:

You will only get an integer overflow if your final number is 10 digits and the first digit is higher or equal to 2.



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

0


source







All Articles