LeetCode 172. Factorial Trailing Zeroes

原题链接在这里:https://leetcode.com/problems/factorial-trailing-zeroes/

题目:

Given an integer n, return the number of trailing zeroes in n!.

Example 1:

Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.

Example 2:

Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.

Note: Your solution should be in logarithmic time complexity.

题解:

求factorial后结尾有多少个0, 就是求有多少个2和5的配对.

但是2比5多了很多,所以就是求5得个数。除此之外,还有一件事情要考虑。诸如25, 125之类的数字有不止一个5. e.g. n = 28, n!我们得到一个额外的5, 并且0的总数变成了6.

0 factorial 是 1. 不用单独考虑n == 0的情况.

n!后缀0的个数 = n!质因子中5的个数

             = floor(n/5) + floor(n/25) + floor(n/125) + ....

Time Complexity: O(logn). Space: O(1).

AC Java:

 1 public class Solution {
 2     public int trailingZeroes(int n) {
 3         int res = 0;
 4         while(n>0){
 5             res += n/5;
 6             n/=5;
 7         }
 8         return res;
 9     }
10 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825040.html