Friday, 1 June 2012

Find the minimum of two numbers without using relational operators

Solution:

1.) Run a loop in which u decrement each number till either of them becomes a zero, and keep incrementing a counter. Return this counter value.
int min(int x, int y){
  int ctr = 0;
  while(x & y){
    x--;y--;ctr++;
  }
  return ctr;
}

2.)
Minimum of x and y will be

y + ((x - y) & ((x - y) >>(sizeof(int) * CHAR_BIT - 1)))
This method shifts the subtraction of x and y by 31 (if size of integer is 32). If (x-y) is smaller than 0, then (x -y)>>31 will be 1. If (x-y) is greater than or equal to 0, then (x -y)>>31 will be 0.
So if x >= y, we get minimum as y + (x-y)&0 which is y.
If x < y, we get minimum as y + (x-y)&1 which is x.


http://www.geeksforgeeks.org/archives/14805

No comments:

Post a Comment