Find the maximum of two numbers without use of comparison operators or if-else

Write a method which finds the maximum of two numbers You should not use if-else or any other comparison operator
EXAMPLE
Input: 5, 10
Output: 10

Solution:
Let’s try to solve this by “re-wording” the problem We will re-word the problem until we get something that has removed all if statements
Rewording 1: If a > b, return a; else, return b
Rewording 2: If (a – b) is negative, return b; else, return a
Rewording 3: If (a – b) is negative, let k = 1; else, let k = 0. Return a – k * (a – b)
Rewording 4: Let c = a – b. Let k = the most significant bit of c. Return a – k * c
We have now reworded the problem into something that fits the requirements for this is below:

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

Comments: Notice the way it tests whether a number is negative or positive, by testing the MSB to be 0 or 1.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: