Quant Memo
Coding/●●●●●

Average two signed integers without overflow

The safe-midpoint trick lo + (hi - lo) // 2 assumes lo <= hi and non-negative indices. But suppose you need the floored average (a+b)/2\lfloor (a + b) / 2 \rfloor of two arbitrary signed integers, either of which may be near the 32- or 64-bit limit, and you cannot assume any ordering or sign.

Compute (a+b)/2\lfloor (a + b)/2 \rfloor with no intermediate that could overflow a fixed-width integer.

Your answer

This one is open-ended. Work it through, then check your reasoning against the full solution.

More Coding questions