package miscellaneous;
//Write a method which finds the maximum of two numbers. You should not use if-else or any other comparison operator
//Say you have two numbers, a=10 and b=2, you want to find max.
//In binary, we know if number is negative then Most Significant Bit(MSB) will be set to 1 and 0 otherwise.
//So if we do a-b and if the result is positive then, MSB will be 0 which says a is greater then only MSB can be 0.
//So by checking the MSB we can decide that if MSB is 0 then a is greater and if MSB is 1 then b is greater
//Now again here we can't check conditional operator to check a...
//formula a-MSB*(a-b) will help. where MSB will be either 1 or 0, if MSB is 0.
//If MSB is 0 it means a is greater, a-MSB*(a-b) = a - 0 * (a-b) = a - 0 = a
//If MSB is 1 it means a is greater, a-MSB*(a-b) = a - 1 * (a-b) = b
// Take example and try.
public class FindMaxOfTwoNumberWithoutComparison {
public static void main(String[] args) {
System.out.println(findMax(-2, 10));
}
private static int findMax( int x, int y){
int z = x - y;
int i = (z >> 31) & 0x1;
int max = x - i * z;
return max;
}
}
Questions on Stack, Queues, Linkedlist, Binary Trees, Sorting, Searching, Graphs etc with solution using Java Language.
Thursday, 21 May 2015
Write a method which finds the maximum of two numbers without using if-else or any other comparison operator
Labels:
Bit Manipulation,
Maths,
miscellaneous
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment