Jun 122012
 

Given 2 unsigned integers, write expressions to find the maximum and minimum of these 2 integers without using either if-else or conditional operator.

Solution:

If the integers are a and b, as given below then the max & min can be computed like below:

   unsigned int a;
   unsigned int b;

   // Computing minimum
   int min = b ^ ( (a^b) & -(a<b) );  

   // Computing maximum
   int max = a ^ ( (a^b) & -(a<b) );   

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)