25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Solutions 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 />

2 6 9<br />

EXAMPLE<br />

Input: 5, 10<br />

Output: 10<br />

SOLUTION<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Additional Review Problems<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 }

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

Saved successfully!

Ooh no, something went wrong!