Factorial Trailing Zeroes LeetCode Solution

Here, We see Factorial Trailing Zeroes LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Factorial Trailing Zeroes LeetCode Solution

Factorial Trailing Zeroes LeetCode Solution

Problem Statement

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

Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.

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

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

Example 3:
Input: n = 0
Output: 0

Factorial Trailing Zeroes LeetCode Solution C++

class Solution {
public:
    int trailingZeroes(int n) {
        int count = 0;
        for (long long i = 5; n / i; i *= 5)
            count += n / i;
        return count;        
    }
};Code language: PHP (php)

Factorial Trailing Zeroes Solution Java

class Solution {
    public int trailingZeroes(int n) {
        int r = 0;
        while (n > 0) {
            n /= 5;
            r += n;
        }
        return r;        
    }
}Code language: PHP (php)

Factorial Trailing Zeroes Solution JavaScript

var trailingZeroes = function(n) {
    let numZeroes = 0;
    for (let i = 5; i <= n; i *= 5) {
        numZeroes += Math.floor(n / i);
    }
    return numZeroes;    
};Code language: JavaScript (javascript)

Factorial Trailing Zeroes Solution Python

class Solution(object):
    def trailingZeroes(self, n):
        if(n < 0):
            return -1
        output = 0
        while(n >= 5):
            n //= 5
            output += n
        return output Code language: HTML, XML (xml)
Scroll to Top