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
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With