Leetcode: Factorial Trailing Zeroes

Factorial Trailing Zeroes



Similar Problems:


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

Note: Your solution should be in logarithmic time complexity.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// Blog link: https://code.dennyzhang.com/factorial-trailing-zeroes
// Basic Ideas:
//  Count how many 5 factors in all number from 1 to n.
//  We have enough 2 to get 10
//
// Complexity: Time O(log(n)), Space O(1)
func trailingZeroes(n int) int {
    res := 0
    for n%5 == 0 {
        n = int(n/5)
        res += 1
    }
    return res
}
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.