LeetCode-Factorial Trailing Zeroes-解题报告

原题链接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;
	}
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值