The average of two integers

What's the difference between

int x = (right + left) / 2; 

and

 int x = left + (right - left) / 2; 

only I got a time limit exception in the first case and got in the second case when performing a binary search

+5
source share
2 answers

The sum of your int variables

right + left (from the limit of integers)

is too large and exceeds the storage limit of integers, so there was an overflow due to the amount, but when you use the differential version, the second

left + (right - left) (within integers)

It is suitable for calculation and favors the machine.

+4
source

The limit (border) int is 2,147,483,647.

Your right+left value does not match int .
But the value of left + (right - left) / 2 less than int , so therefore the second expression works fine.

if you add such large numbers, use long .

+2
source

Source: https://habr.com/ru/post/1239224/


All Articles