*[Lintcode]Trailing Zeros

来源:互联网 发布:杜兰特各赛季数据统计 编辑:程序博客网 时间:2024/05/01 19:23

Write an algorithm which computes the number of trailing zeros in n factorial.

Example

11! = 39916800, so the out should be 2

计算最后0的个数,因为产生0主要需要2或5,所以只需要计算2和5一共有多少对即可。同时2的个数远多于5,所以这里只需要计算5在连乘里一共有多少个即可。这里先计算所有包含一个5的数字个数,在计算包含两个5的数字个数


class Solution {    /*     * param n: As desciption     * return: An integer, denote the number of trailing zeros in n!     */    public long trailingZeros(long n) {        long count = 0;        while(n > 0) {            count += n / 5;            n = n / 5;        }        return count;    }};


0 0
原创粉丝点击