LeetCode 172. Factorial Trailing Zeroes

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

思路:

阶乘末尾有多少零,取决于结果中有多少个10。而又多少个10又取决于结果中有多少个5(2的数量是远大于5的,因此数5的数量即可)。

数5的个数直接n/5即可,但是要注意25,125等特殊情况,需要将额外的5计算进来。这些情况计算n/5^2, n/5^3, ...

类似数学题做过一遍基本就会了。

class Solution {
public:
    int trailingZeroes(int n) {
        int count=0;
        while (n>0){
            count += n/5;
            n = n/5;
        }
        return count;
    }
};

猜你喜欢

转载自www.cnblogs.com/hankunyan/p/8975396.html