This is a classic interview question: You are asked to write a function that returns a bigger number of both, without using any comparison operator, such as if, or ternary operator (e.g. ?).
1 2 3 | int max(int a, int b) { // TODO } |
int max(int a, int b) { // TODO }
This is to return (a > b ? a : b); If a is larger than b returns a otherwise b. We let
So, the target is to compute the value of k, which is the MSB (most significant bit, the signed bit) of the integer c, negative means a smaller than b.
Thus, we have the following solution (bit right shift 31 positions and we have the signed bit at the right-most bit, the least significant bit (LSB)) :
1 2 3 4 5 6 | inline int max(int a, int b) { int c = a - b; int k = (c >> 31) & 1; return (a - k * c); } |
inline int max(int a, int b) { int c = a - b; int k = (c >> 31) & 1; return (a - k * c); }
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: How to Find Out Whether a Machine is Big Endian or Little Endian in C/C++?
Next Post: Bit Manipulation: How to Set All Bits Between i and j in N equal to M?