WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Coding Interview Essentials Β· Bit Manipulation Problems Β· question 87 of 120

Can you find the maximum of two integers without using if-else or any other comparison operator?

πŸ“• Buy this interview preparation book: 120 Coding Interview Essentials questions & answers β€” PDF + EPUB for $5

it is possible to determine the maximum of two integers without using if-else or any other comparison operator. This can be done using bitwise operators and principles of arithmetic in the world of computer science.

Let’s denote the two numbers as β€˜aβ€˜ and β€˜bβ€˜.

The key idea is to get the difference between β€˜bβ€˜ and β€˜aβ€˜, and then extract the sign of this difference, which can either be 0 when β€˜b >= aβ€˜ or 1 when β€˜b < aβ€˜.

Firstly, notice that we can obtain the sign of any number β€˜xβ€˜ by performing the bitwise AND operation on β€˜xβ€˜ and the most significant bit mask, and then shifting right by 31 bits (on a 32-bit system). This gives us 1 if β€˜xβ€˜ is negative and 0 if β€˜xβ€˜ is non-negative.

Therefore, the expression for the sign of the difference β€˜b - aβ€˜ is:

diff = b - a
sign = (diff & (1 << 31)) >> 31

So, now we have the sign of the difference, we can use it to return either β€˜aβ€˜ or β€˜bβ€˜ as the maximum.

We can create an expression that equals β€˜aβ€˜ when β€˜sign = 0β€˜ and β€˜bβ€˜ when β€˜sign = 1β€˜, which is equivalent to:

maximum = a * (sign ^ 1) + b * sign

Here is a python code snippet which demonstrates this:

def maxOfTwo(a, b):
    diff = b - a
    sign = (diff & (1 << 31)) >> 31 # get the sign of diff
    maximum = a * (sign ^ 1) + b * sign
    return maximum

This solution works because the bitwise XOR of any bit with 1 flips the bit, whereas XOR with 0 leaves it unchanged.

Keep in mind that this solution may not work as expected with overflow integers and corner cases should be handled properly in a production-level code.

Moreover, it’s worth noting that this solution assumes the numbers are 32 bits wide, but it can be easily generalized to work for numbers of any bit width.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview β€” then scores it.
πŸ“ž Practice Coding Interview Essentials β€” free 15 min
πŸ“• Buy this interview preparation book: 120 Coding Interview Essentials questions & answers β€” PDF + EPUB for $5

All 120 Coding Interview Essentials questions Β· All topics