25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Solutions 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 />

CareerCup com<br />

pg 89<br />

Trailing zeros are contributed by pairs of 5 and 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, and 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 and 20, and 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, and 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 />

2 6 8

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

Saved successfully!

Ooh no, something went wrong!