LeetCode-Factorial Trailing Zeroes-解题报告

来源:互联网 发布:进程间数据共享的方式 编辑:程序博客网 时间:2024/05/04 20:00

原题链接https://leetcode.com/problems/factorial-trailing-zeroes/

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

Note: Your solution should be in logarithmic time complexity.

求n!的尾部有多少个0.


首先想到的就是分解质因数,因为10 = 2 * 5, 所以只需要将1~n的2和5的个数数出来,返回个数最少的,很明显5的个数肯定是最少的。


如果直接这样做,我会告诉你超时了么。 哈哈


所以的换个方法。

给定的n

n  = 5 * a + b; 如果  1 < j <= a, j*5 <= n,所以5至少有j个

n = 5^2 * c + d; 同样的道理 可以分解为两个5的个数有c个,当然在上一次一个5的情况包含了一次2个5的情况所以 只需要加一次c即可。

一直到 n/(5^m) = 0;


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





0 0
原创粉丝点击