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

Create successful ePaper yourself

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

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

19.1 Write a function to swap a number in place without temporary variables.<br />

pg 89<br />

SOLUTION<br />

This is a classic interview problem. If you haven’t heard this problem before, you can approach<br />

it by taking <strong>the</strong> difference between a <strong>and</strong> b:<br />

1 public static void swap(int a, int b) {<br />

2 a = b - a; // 9 - 5 = 4<br />

3 b = b - a; // 9 - 4 = 5<br />

4 a = a + b; // 4 + 5 = 9<br />

5<br />

6 System.out.println(“a: “ + a);<br />

7 System.out.println(“b: “ + b);<br />

8 }<br />

You can <strong>the</strong>n optimize it as follows:<br />

1 public static void swap_opt(int a, int b) {<br />

2 a = a^b;<br />

3 b = a^b;<br />

4 a = a^b;<br />

5<br />

6 System.out.println(“a: “ + a);<br />

7 System.out.println(“b: “ + b);<br />

8 }<br />

2 6 5<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!