Leetcode - Factorial Trailing Zeros

Ji Kim·2020년 8월 17일
0

Algorithm

목록 보기
7/34

Leetcode : Factorial Trailing Zeros

Description

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

Example 1

Input

3

Output

0
// 3! = 6, no trailing zero.

Example 2

Input

5

Output

0
// 5! = 120, 1 trailing zero.

Approach

Trailing Zero is always produced by 2 * 5, therefore count the numbers of 2 and 5 within the input - n.

Solution (C++)

class Solution {
public:
    unsigned long long fives = 5; 
    unsigned long long division = 1; 
    unsigned long long answer = 0;
    
    int trailingZeroes(int n) {
        while (division > 0)
        {
            division = floor(n / fives);
            answer = answer + division;
            fives = fives * 5; 
        }
        
        return answer; 
    }
};

Result

Runtime : 0ms
Memory Usage : 6.1MB
Runtime Beats 100% of C++ Submission

profile
if this then that

0개의 댓글