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.