You study the coding problem with a number of restrictions on operators and language constructs for performing given tasks.
The first problem is to return -1 without using the - operator.
On machines representing negative numbers with two additions, the value -1 is represented with all bits set to 1 , therefore ~0 is evaluated as -1 :
int minusOne(void) {
Other problems in the file are not always performed correctly. The second problem, returning a boolean representing the fact that the value of a int will correspond to the 16-bit character short has a drawback:
int fitsShort(int x) { return !(((x << 16) >> 16) ^ x); }
The left bias of a negative value or a number whose biased value is outside the range of int has undefined behavior, the right bias of a negative value is determined by the implementation, so the above solution is incorrect (although this is probably expected to be a solution).
chqrlie Sep 23 '17 at 13:49 on 2017-09-23 13:49
source share