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