Monday, January 26, 2015

Factorial Trailing Zeroes

Factorial Trailing Zeroes

 Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.

------------------------------ thinking -----------------------------------------------
the number of 0 is decided by how many 5 it has in the array, because the number of 2 is always bigger than 5.
----------------------------- mistakes -----------------------------------------------
When I firstly implemented it, I think of 5 and 10 separately, which is obviously wrong. Because 10 is constructed by 2 & 5!
---------------------------- codes ---------------------------
class Solution {
public:
    int trailingZeroes(int n) {
        int result = 0;
        int cur_num = n;
        while (cur_num > 0) {
            result += cur_num / 5;
            cur_num /= 5;
        }
        return result;
    }
};

No comments:

Post a Comment