Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain this snippet which finds the maximum of two integers without using if-else or any other comparison operator?

Find the maximum of two numbers. You should not use if-else or any other comparison operator. I found this question on online bulletin board, so i thought i should ask in StackOverflow

EXAMPLE Input: 5, 10 Output: 10

I found this solution, can someone help me understand these lines of code

int getMax(int a, int b) {       int c = a - b;       int k = (c >> 31) & 0x1;       int max = a - k * c;       return max;   } 
like image 347
SuperMan Avatar asked Jan 23 '11 07:01

SuperMan


2 Answers

int getMax(int a, int b) {     int c = a - b;     int k = (c >> 31) & 0x1;     int max = a - k * c;     return max; } 

Let's dissect this. This first line appears to be straightforward - it stores the difference of a and b. This value is negative if a < b and is nonnegative otherwise. But there's actually a bug here - if the difference of the numbers a and b is so big that it can't fit into an integer, this will lead to undefined behavior - oops! So let's assume that doesn't happen here.

In the next line, which is

int k = (c >> 31) & 0x1; 

the idea is to check if the value of c is negative. In virtually all modern computers, numbers are stored in a format called two's complement in which the highest bit of the number is 0 if the number is positive and 1 if the number is negative. Moreover, most ints are 32 bits. (c >> 31) shifts the number down 31 bits, leaving the highest bit of the number in the spot for the lowest bit. The next step of taking this number and ANDing it with 1 (whose binary representation is 0 everywhere except the last bit) erases all the higher bits and just gives you the lowest bit. Since the lowest bit of c >> 31 is the highest bit of c, this reads the highest bit of c as either 0 or 1. Since the highest bit is 1 iff c is 1, this is a way of checking whether c is negative (1) or positive (0). Combining this reasoning with the above, k is 1 if a < b and is 0 otherwise.

The final step is to do this:

int max = a - k * c; 

If a < b, then k == 1 and k * c = c = a - b, and so

a - k * c = a - (a - b) = a - a + b = b 

Which is the correct max, since a < b. Otherwise, if a >= b, then k == 0 and

a - k * c = a - 0 = a 

Which is also the correct max.

like image 135
templatetypedef Avatar answered Oct 06 '22 11:10

templatetypedef


Here we go: (a + b) / 2 + |a - b| / 2

like image 35
mike.dld Avatar answered Oct 06 '22 12:10

mike.dld