[LeetCode]172. Factorial Trailing Zeroes

阶乘含有多少个0

Posted by JinFei on November 12, 2021

题目描述

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

Example1:

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

Example2:

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

NOTE:

  • Your solution should be in logarithmic time complexity.

解题思路

  • 求阶乘末尾0的个数
  • 实质是求在乘的过程中,有多少个10
  • 10可分解成5*2,其中2的个数又远大于5,即本题计算给定的数字含有5的个数
class Solution {
public:
    int trailingZeroes(int n) {
        int res = 0;
        while(n){
            res += n / 5;
            n /= 5;
        }
        return res;
    }
    
};