The idea of implementing subtraction is good.
int sub = x + (~y+1);
Here you just need to check if sub negative, i.e. extract your bit sign. This is where technical difficulties arise.
Suppose x and y are unsigned 32-bit integers. Then the result of the subtraction can be represented by a signed 33-bit integer (check its minimum and maximum values to see this). That is, using the expression x + (~y+1) does not directly help, because it will overflow.
What if x and y were 31-bit unsigned numbers? Then x + (~y+1) can be represented by a 32-bit signed number, and its signed bit tells us if x y less:
answer(x, y) := ((x + (~y+1)) >> 31) & 1
To convert x and y from 32 bits to 31 bits, separate their MSB (most significant bit) and all other 31 bits into different variables:
msb_x = (x >> 31) & 1; msb_y = (y >> 31) & 1; x_without_msb = x << 1 >> 1; y_without_msb = y << 1 >> 1;
Then consider 4 possible combinations of their MSB:
if (msb_x == 0 && msb_y == 0) return answer(x_without_msb, y_without_msb); else if (msb_x == 1 && msb_y == 0) return 0; // x is greater than y else if (msb_x == 0 && msb_y == 1) return 1; // x is smaller than y else return answer(x_without_msb, y_without_msb);
Converting all these if-statements to one big ugly logical expression is an exercise for the reader.
source share