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 20 | Hard<br />

10<br />

11 // Counts 2s from first digit<br />

12 int nTwosFirst = 0;<br />

13 if (first > 2) nTwosFirst += power;<br />

14 else if (first == 2) nTwosFirst += remainder + 1;<br />

15<br />

16 // Count 2s from all o<strong>the</strong>r digits<br />

17 int nTwosO<strong>the</strong>r = first * count2sR(power - 1) + count2sR(remainder);<br />

18<br />

19 return nTwosFirst + nTwosO<strong>the</strong>r;<br />

20 }<br />

We can also implement this algorithm iteratively:<br />

1 public static int count2sI(int num) {<br />

2 int countof2s = 0, digit = 0;<br />

3 int j = num, seendigits=0, position=0, pow10_pos = 1;<br />

4 /* maintaining this value instead of calling pow() is an 6x perf<br />

5 * gain (48s -> 8s) pow10_posMinus1. maintaining this value<br />

6 * instead of calling Numof2s is an 2x perf gain (8s -> 4s).<br />

7 * overall > 10x speedup */<br />

8 while (j > 0) {<br />

9 digit = j % 10;<br />

10 int pow10_posMinus1 = pow10_pos / 10;<br />

11 countof2s += digit * position * pow10_posMinus1;<br />

12 /* we do this if digit , or = 2<br />

13 * Digit < 2 implies <strong>the</strong>re are no 2s contributed by this<br />

14 * digit.<br />

15 * Digit == 2 implies <strong>the</strong>re are 2 * numof2s contributed by<br />

16 * <strong>the</strong> previous position + num of 2s contributed by <strong>the</strong><br />

17 * presence of this 2 */<br />

18 if (digit == 2) {<br />

19 countof2s += seendigits + 1;<br />

20 }<br />

21 /* Digit > 2 implies <strong>the</strong>re are digit * num of 2s by <strong>the</strong> prev.<br />

22 * position + 10^position */<br />

23 else if(digit > 2) {<br />

24 countof2s += pow10_pos;<br />

25 }<br />

26 seendigits = seendigits + pow10_pos * digit;<br />

27 pow10_pos *= 10;<br />

28 position++;<br />

29 j = j / 10;<br />

30 }<br />

31 return(countof2s);<br />

32 }<br />

CareerCup com<br />

2 8 4

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

Saved successfully!

Ooh no, something went wrong!