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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

19.3 Write an algorithm which computes <strong>the</strong> number of trailing zeros in n factorial.<br />

SOLUTION<br />

pg 89<br />

Trailing zeros are contributed by pairs of 5 <strong>and</strong> 2, because 5*2 = 10. To count <strong>the</strong> number of<br />

pairs, we just have to count <strong>the</strong> number of multiples of 5. Note that while 5 contributes to<br />

one multiple of 10, 25 contributes two (because 25 = 5*5).<br />

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

2 int count = 0;<br />

3 if (num < 0) {<br />

4 System.out.println(“Factorial is not defined for < 0”);<br />

5 return 0;<br />

6 }<br />

7 for (int i = 5; num / i > 0; i *= 5) {<br />

8 count += num / i;<br />

9 }<br />

10 return count;<br />

11 }<br />

Let’s walk through an example to see how this works: Suppose num = 26. In <strong>the</strong> first loop, we<br />

count how many multiples of five <strong>the</strong>re are by doing 26 / 5 = 5 (<strong>the</strong>se multiples are 5, 10, 15,<br />

20, <strong>and</strong> 25). In <strong>the</strong> next loop, we count how many multiples of 25 <strong>the</strong>re are: 26 / 25 = 1 (this<br />

multiple is 25). Thus, we see that we get one zero from 5, 10, 15 <strong>and</strong> 20, <strong>and</strong> two zeros from<br />

25 (note how it was counted twice in <strong>the</strong> loops). Therefore, 26! has six zeros.<br />

OBSERVATIONS AND SUGGESTIONS:<br />

» » This is a bit of a brain teaser, but it can be approached logically (as shown above). By<br />

thinking through what exactly will contribute a zero, <strong>and</strong> what doesn’t matter, you can<br />

come up with a solution. Again, be very clear in your rules up front so that you can<br />

implement this correctly.<br />

CareerCup.com<br />

2 6 8

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

Saved successfully!

Ooh no, something went wrong!