I'm creating a Reverse Polish Calculator and am having issues with saturation. I've implemented a stack, and have found the largest number I can get to without having the issue is 2147483647. So if I push this number to the stack, then add 1, the result I get is -2147483648 (negative). What I need to do is instead of returning this negative number, return the original number 2147483647. Basically have this as a limit. The same applies to the negative side of things, where the limit is -2147483648. Let me know if I have missed any info or you need to see code.
Asked
Active
Viewed 655 times
1 Answers
0
The largest int
value is 2147483647
and the smallest is -2147483648
. int
values wrap around, so when you add 1
to 2147483647
you get -2147483648
and when you subtract 1
from -2147483648
you get 2147483647
.
If you don't want this behaviour you can do
int a = 2147483647;
a += 1.0; // a is still 2147483647
or
int a = 2147483647;
int b = (int) (a + 1.0); // b is also 2147483647
These work because a + 1.0
is calculated using double
(no overflow) and the result is converted back to an int
using the rule that numbers bigger than Integer.MAX_VALUE
just become Integer.MAX_VALUE
.

Paul Boddington
- 37,127
- 10
- 65
- 116
-
I couldn't seem to get his solution to work? Using doubles I am returned with this 2.147483647E9. Any idea? – George Burslem Nov 26 '15 at 18:29
-
@GeorgeBurslem No, it won't work if you have any variables of type `double`. All the variables must have type `int`. If you want a solution using `int` you can do `int b = a == Integer.MAX_VALUE ? a : a + 1;` to add 1 and `int c = a == Integer.MIN_VALUE ? a : a - 1;` for subtracting 1. – Paul Boddington Nov 26 '15 at 18:31