Reputation: 319
What is the difference between
int x = (right + left) / 2;
and
int x = left + (right - left) / 2;
just I got time limit exception in first case and got accepted in second case when doing binary search
Upvotes: 6
Views: 691
Reputation: 1421
The int limit(bound) is 2,147,483,647.
Your right+left
value is out of bound of int
.
But left + (right - left) / 2
value is less than int
bound, so that is why second expression works fine.
if you adding such big numbers, use long
.
Upvotes: 2
Reputation: 376
The sum of your int variables
right + left (out of integers limit)
is too big and exceeds integers storage limit that's why there was an over flow because of the sum, but when you use the difference version the second one
left + (right - left) (within integers limit)
it suits the calculation and is in favor of the machine.
Upvotes: 3