导航

LeetCode 172. Factorial Trailing Zeroes

Posted on 2016-04-12 23:59  CSU蛋李  阅读(108)  评论(0编辑  收藏  举报

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

Note: Your solution should be in logarithmic time complexity.

给一个数n,看他的阶乘中最后有几个0

10是由5*2得到的,在阶乘中,明显2的个数要比5的个数多,因而限制条件是有多少个5

n/25贡献两次,又当n/5时,已贡献一次,因而ret=n/5+n/25+..

同理n/125贡献3次,n/25和n/5时已贡献两次,因而ret=n/5+n/25+n/125+...

 

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