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 10 | Ma<strong>the</strong>matical<br />

27<br />

28 /* Multiply a by b by adding a to itself b times */<br />

29 public static int FnTimes(int a, int b) {<br />

30 if (a < b) return FnTimes(b, a); // algo is faster if b < a<br />

31 int sum = 0;<br />

32 for (int iter = abs(b); iter > 0; --iter) sum += a;<br />

33 if (b < 0) sum = FnNegate(sum);<br />

34 return sum;<br />

35 }<br />

36<br />

37 /* Divide a by b by literally counting how many times does b go into<br />

38 * a. That is, count how many times you can subtract b from a until<br />

39 * you hit 0. */<br />

40 public static int FnDivide(int a, int b) throws<br />

41 java.lang.ArithmeticException {<br />

42 if (b == 0) {<br />

43 throw new java.lang.ArithmeticException(“Divide by 0.”);<br />

44 }<br />

45 int quotient = 0;<br />

46 int divisor = FnNegate(abs(b));<br />

47 int divend; /* dividend */<br />

48 for (divend = abs(a); divend >= abs(divisor); divend += divisor) {<br />

49 ++quotient;<br />

50 }<br />

51 if (DifferentSigns(a, b)) quotient = FnNegate(quotient);<br />

52 return quotient;<br />

53 }<br />

OBSERVATIONS AND SUGGESTIONS<br />

»»<br />

A logical approach of going back to what exactly multiplication <strong>and</strong> division do comes<br />

in h<strong>and</strong>y. Remember that. All (good) interview problems can be approached in a logical,<br />

methodical way!<br />

»»<br />

The interviewer is looking for this sort of logical work-your-way-through-it approach.<br />

»»<br />

This is a great problem to demonstrate your ability to write clean code—specifically,<br />

to show your ability to re-use code. For example, if you were writing this solution <strong>and</strong><br />

didn’t put FnNegate in its own method, you should move it out once you see that you’ll<br />

use it multiple times.<br />

» » Be careful about making assumptions while coding. Don’t assume that <strong>the</strong> numbers are<br />

all positive, or that a is bigger than b.<br />

1 9 1<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Concepts <strong>and</strong> Algorithms

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

Saved successfully!

Ooh no, something went wrong!