May 082017
 

How will you find minimum of three integers without using any comparison operator ?

Small disclaimer before proceeding, Such questions are not coding interview questions, it is rather like trick question. 

There can be multiple ways to do that, below are some of them:

1. Use decrement

The smallest number is nearest to zero.

int minimum(int a, int b, int c)
{
  int count = 0;
  while ( a != 0 && b != 0 && c != 0 )
  {
      a--;  b--; c--; count++;
  }
  return count;
}

But the time taken by this code is O(n), where n is the smallest. If we use comparison operator, then it takes constant time O(1).

Below is the constant time method to find minimum of three numbers.

2. Using Division operator

We know that integer division will result in zero if the denominator is smaller. i.e

a/b = 0 (if b <a)

We use this fact to find minimum of two and then further it can be used to find minimum of three

int minOfTwo(int a, int b)
{
   if(a/b != 0)
      return a;
   else 
      return b;
}

int minOfThree(int a, int b, int c)
{
  return minOfTwo(a, minOfTwo(b, c));
}

3. Using XOR operator

If the questions is that find minimum (or maximum) without using branching then this post can be used. In this case however, we cannot use it because the question is without using conditional operator.

 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)