1

Suppose, I have a simple method:

public int add(int a, int b) {
    return a + b;
}

If I run it with max int values

add(2147483647, 2147483647);

I get -2. I found that if we overflow int then we go to min integer value (-2147483648) and keep adding.

Let's do some math. If I add 2147483647 + 2147483647 I should get -1, because

-2147483648 + 2147483647 = -1

So why do I get -2?

0

2 Answers 2

6

Think of it like this:

  2147483647 + 2147483647
= 2147483647 + ( 1 + 2147483646 )
= ( 2147483647 + 1 ) + 2147483646
= -2147483648 + 2147483646  // Because of overflow
= -2

That is, to get the lefthand 2147483647 to overflow, you had to add 1 to it. That 1 came from the right-hand 2147483647, so now there is only 2147483646 left.

Of course, internally it's done by 2s-complement addition, not by adding 1s until you reach the end. The above just clarifies the maths.

Sign up to request clarification or add additional context in comments.

Comments

5

Lets do some math. Max is 2147483647 but min is -2147483648.

2147483647 + 1 = -2147483648
2147483647 + 2 = -2147483647
...
2147483647 + n = -2147483648 + n - 1

which for n = 2147483647 gives us

2147483647 + 2147483647 = -2147483648 + 2147483647 - 1 = -1 - 1 = -2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.