Trailing Zeros
Write an algorithm which computes the number of trailing zeros in n factorial.
Example
11! = 39916800, so the out should be 2
1 /* 2 * param n: As desciption 3 * return: An integer, denote the number of trailing zeros in n! 4 我们会发现: the number of 2s in prime factors is always more than or equal 5 to the number of 5s. So if we count 5s in prime factors, we are done. 6 7 How to count total number of 5s in prime factors of n!? A simple way is 8 to calculate floor(n/5). 9 10 问题转化为求阶乘过程中质因子5的个数,但是要注意25能提供2个5,125能提供3个5.... 11 所以,count= floor(n/5) + floor(n/25) + floor(n/125) + .... 12 */ 13 14 public class Solution { 15 public int trailingZeroes(int n) { 16 if (n < 0) return 0; 17 18 int r = 0; 19 while (n > 0) { 20 n /= 5; 21 r += n; 22 } 23 return r; 24 } 25 }

浙公网安备 33010602011771号