> Then the majority come up with (a / 2) + (b / 2) until they run the unit tests and realize it's wrong.
Why is that wrong?
Why is that wrong?
In general, even with floating point numbers you can get different results by rounding implicitly or intentionally the intermediate values versus the end result.
But in computing, assuming we are only dealing with integers, 1/2 == 0. So 1/2 + 1/2 returns 0.
"This will be too low if the original addition contained a carry from bit 0 to bit 1, which happens if bit 0 is set in both of the terms, so we detect that case and make the necessary adjustment."
return (a / 2) + (b / 2) + (a & b & 1);