In some conditions like Segment Tree or Binary Search, I have to get the average value of 2 number.
An easy solution is mid = (a + b) / 2
. But when it comes to a
and b
have the same plus-minus signs, The a + b
thing will overflow. For example, 1234567 + 2147483647
, -1234567 + (-2147483647)
in int32 type.
I searched online and got to know mid = (b - a) / 2 + a
, it can avoid the situation above, but still not perfect. When it comes to a
and b
have the different plus-minus signs, mid = (a + b) / 2
won't overflow but (b - a) / 2 + a
will. For example, -2147483648 + 2147483647
in int32 type.
To thoroughly solve this problem, I've written the code in pic below. I divide the 2 situations by the plus-minus signs. (I use some bit operations to improve its efficiency.) But it is way too complex for such a simple problem, right?
Is there some elegant solution to this problem?
I tried to divide the problem to 2 situations and solve them respectively. But I still want a more elegant solution.