7 ms·
The proposed solution for C and C++ mid = ((unsigned int)low + (unsigned int)high)) >> 1; in the blog may still be wrong if the sum ((unsigned)low + (unsign
by mnaydin 8y ago
The proposed solution for C and C++
mid = ((unsigned int)low + (unsigned int)high)) >> 1;
in the blog may still be wrong if the sum ((unsigned)low + (unsigned)high)) produces a carry.
- eesmith 8y agoMax 32-bit signed int is (1<<31)-1 . Twice that is 1<<32-2. Max 32-bit unsigned int is (1<<32)-1. Therefore, if 'low' and 'high' are non-negative 32-bit signed integers, it is impossible for their sum, when the values are first cast to 32-bit unsigned integers, to produce a carry.
- mnaydin 8y agoTrue. I had thought low and high could be unsigned originally, in which case casting to unsigned is redundant, then the sum would produce a carry.