[Leetcode]4 Mar. 2025. Count Trailing Zeros in Factorial

Description:

Given an integer $n$ , return the number of trailing zeros in $n!$ (n factorial).

Factorial is defined as:
$$
n! = n \times (n – 1) \times (n – 2) \times \dots \times 3 \times 2 \times 1
$$

Examples:

Example 1:
Input: n = 3
Output: 0
Explanation: 3! = 6, which has no trailing zeros.

Example 2:
Input: n = 5
Output: 1
Explanation: 5! = 120, which has one trailing zero.

Example 3:
Input: n = 0
Output: 0

Constraints:

  • $0 \leq n \leq 10^4$

class Solution {
public:
    int trailingZeroes(int n) {
        int count;
        while(n >= 5){
            n = n / 5;
            count += n;
        }
        return count;
    }
};

/*
## Counting 5 as a factor.

We Need To Determine how many times "10" appears as a factor in the product.

10 is formed by multiplying 2 & 5, we can only count 5 as a factor.

For example:
- 3! = 3*2*1 = 6 -> +0
- 5! = 5*4*3*2*1 = 120 -> +1
- 10! = 10*9*...*3*2*1 = 3628800 -> +2
*/
C++

Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

en_USEN