27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 19 | Moderate<br />

19.4 Write a method which finds <strong>the</strong> maximum of two numbers. You should not use if-else<br />

or any o<strong>the</strong>r comparison operator.<br />

EXAMPLE<br />

Input: 5, 10<br />

Output: 10<br />

SOLUTION<br />

pg 89<br />

Let’s try to solve this by “re-wording” <strong>the</strong> problem. We will re-word <strong>the</strong> problem until we get<br />

something that has removed all if statements.<br />

Rewording 1: If a > b, return a; else, return b.<br />

Rewording 2: If (a - b) is negative, return b; else, return a.<br />

Rewording 3: If (a - b) is negative, let k = 1; else, let k = 0. Return a - k * (a - b).<br />

Rewording 4: Let c = a - b. Let k = <strong>the</strong> most significant bit of c. Return a - k * c.<br />

We have now reworded <strong>the</strong> problem into something that fits <strong>the</strong> requirements. The code<br />

for this is below.<br />

1 int getMax(int a, int b) {<br />

2 int c = a - b;<br />

3 int k = (c >> 31) & 0x1;<br />

4 int max = a - k * c;<br />

5 return max;<br />

6 }<br />

2 6 9<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Additional Review Problems

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!