25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

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.

Solutions to Chapter 10 | Ma<strong>the</strong>matical<br />

10 4 Write a method to implement *, - , / operations You should use only <strong>the</strong> + operator<br />

SOLUTION<br />

CareerCup com<br />

pg 68<br />

With an understanding of what each operation (minus, times, divide) does, this problem can<br />

be approached logically<br />

» Subtraction should be relatively straightforward, as we all know that a - b is <strong>the</strong> same<br />

thing as a + (-1)*b<br />

» Multiplication: we have to go back to what we learned in grade school: 21 * 3 = 21 + 21<br />

+ 21 It’s slow, but it works<br />

» Division is <strong>the</strong> trickiest, because we usually think of 21 / 3 as something like “if you divide<br />

a 21 foot board into 3 pieces, how big is each piece?” If we think about it <strong>the</strong> o<strong>the</strong>r way<br />

around, it’s a little easier: “I divided a 21 foot board in x pieces and got pieces of 3 feet<br />

each, how many pieces were <strong>the</strong>re?” From here, we can see that if we continuously subtract<br />

3 feet from 21 feet, we’ll know how many pieces <strong>the</strong>re are That is, we continuously<br />

subtract b from a and count how many times we can do that<br />

1 /* Flip a positive sign to negative, or a negative sign to pos */<br />

2 public static int FnNegate(int a) {<br />

3 int neg = 0;<br />

4 int d = a < 0 ? 1 : -1;<br />

5 while (a != 0) {<br />

6 neg += d;<br />

7 a += d;<br />

8 }<br />

9 return neg;<br />

10 }<br />

11<br />

12 /* Subtract two numbers by negating b and adding <strong>the</strong>m */<br />

13 public static int FnMinus(int a, int b) {<br />

14 return a + FnNegate(b);<br />

15 }<br />

16<br />

17 /* Check if a and b are different signs */<br />

18 public static boolean DifferentSigns(int a, int b) {<br />

19 return ((a < 0 && b > 0) || (a > 0 && b < 0)) ? true : false;<br />

20 }<br />

21<br />

22 /* Return absolute value */<br />

23 public static int abs(int a) {<br />

24 if (a < 0) return FnNegate(a);<br />

25 else return a;<br />

26 }<br />

1 9 0

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

Saved successfully!

Ooh no, something went wrong!