172. Factorial Trailing Zeroes

71 阅读1分钟

题目描述

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.

解题思路

首先,我们可以使用暴力解法, 计算出n!, 然后在从尾部遍历, 计算出尾部有几个0, 但是这样的效率肯定很低, 我们考虑使用数学的方法在解题, 求5的因子.
尾部有0, 说明阶乘的过程中, 有 5 * 2 = 10 出现, 题目就转化为求有多少对 5*2, 因为5>2, 所以只要求出有多少个5, 就至少有对应的2与之对应. 其中特殊的 5 * 5 = 25, 有2个5, 肯定可以前边的 24 22相乘得到2个0

示例代码

func trailingZeroes(_ n: Int) -> Int {
    var result = 0
    var temp = n
    while temp > 0 {
        result += temp / 5
        temp /= 5
    }
    return result
}