leetcode刷题,总结,记录 ,备忘 172

leetcode172 Factorial Trailing Zeroes

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

Note: Your solution should be in logarithmic time complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

求阶乘的尾数0的个数。首先想到的就是2x5,才会得0,又由于2的数量是肯定比5多的,所以只要计算5的数量即可,一开始我也比较天真,直接计算n / 5的结果,但是不行,因为还有25的情况,是5的2次方,需要多加个1,后面还有125,625等。所以使用循环每次除以5,将结果累加。
class Solution {
public:
    int trailingZeroes(int n) {
        int sum = 0;
        
        while (n)
        {
            sum += n / 5;
            n /= 5;
        }
        
        return sum;
    }
};

你可能感兴趣的:(leetcode刷题,总结,记录 ,备忘 172)