Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detecting 32 bit integer overflow

Tags:

c++

algorithm

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.

like image 346
sarosh mirza Avatar asked Mar 27 '26 07:03

sarosh mirza


1 Answers

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.

like image 113
Mike Nakis Avatar answered Mar 28 '26 21:03

Mike Nakis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!