Let's make this one less mysterious. For 172. Factorial Trailing Zeroes, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are trailingZeroes.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 4 ms, faster than 56.81% of C++ online submissions for Factorial Trailing Zeroes.
02//Memory Usage: 7.5 MB, less than 100.00% of C++ online submissions for Factorial Trailing Zeroes.
03
04class Solution {
05public:
06 int trailingZeroes(int n) {
07 //matching count of 2 and 5
08 int two_count = 0, five_count = 0;
09
10 for(int i = 1; n >= pow(5,i); i++){
11 five_count += n/pow(5,i);
12 }
13
14 for(int i = 1; n >= pow(2,i); i++){
15 two_count += n/pow(2,i);
16 }
17
18 return min(two_count, five_count);
19 }
20};
Cost