LintCode-2(Trailing Zeros)

关于

lintcode系列,第2题,题目网址:https://www.lintcode.com/problem/trailing-zeros/description

描述

设计一个算法,计算出 n 阶乘中尾部零的个数,要求 O(logN) 的时间复杂度。

思路

先举几个例子看看规律:

  • 5! = 5 * 4 * 3 * 2 * 1 = 120
  • 11! = 11 * 10 * 9 * …… * 5 * 4 * 3 * 2 = 39916800
  • 25! = 25 * 24 * …… * 20 * …… * 15 * …… * 10 * …… * 5 * …… = ……000000 (6个0)

可以看到一个 5 和一个 2 就可以产生一个 0,而在阶乘中,5 的个数是一定少于 2 的个数的,所以只要判断 n 有多少个 5 就好了。

C++实现

class Solution {
public:
    /*
     * @param n: A long integer
     * @return: An integer, denote the number of trailing zeros in n!
     */
    long long trailingZeros(long long n) {
      long long a = 0;
        while(n != 0){
          a = a + n/5;
          n = n/5;
        }
        return a;
    }
};
posted @ 2018-08-22 19:18  tonasy  阅读(176)  评论(0编辑  收藏  举报