[刷题防痴呆] 0172 - 阶乘后的零 (Factorial

2021-11-07  本文已影响0人  西出玉门东望长安

题目地址

https://leetcode.com/problems/factorial-trailing-zeroes/description/

题目描述

172. 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.

思路

最终尾随零的数量之和质因子中2和5的数量有关, 很容易想到质因子5的数量一定会比2少, 所以只需要算出n!的质因子5的数量即可.

关键点

代码

class Solution {
    public int trailingZeroes(int n) {
        int zeroCount = 0;
        while (n > 0) {
            n /= 5;
            zeroCount += n;
        }
        
        return zeroCount;
    }
}
上一篇下一篇

猜你喜欢

热点阅读