LeeCode#172: Factorial Trailing Zeroes

Description

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

Example

Example 1:

Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.

Solution

题目要求求出阶乘末尾有多少个0。

首先,末尾有多少个0取决于有多少个10相乘,而10由2×5得到,因此末尾0的个数取决于2与5的组合数。例如,5! = (5 × 4 × 3 × 2 × 1) = (5 × 2 × 2 × 3 × 2 × 1) = 120,因为阶乘中有三个2和一个5,只有一个5×2的组合,所以末尾0的个数也为一个。

又由于阶乘中2的个数总是大于等于5的个数,因此只要计算5的个数就可以了。除此之外,像25这样的数字有5、10、15、20、25,但这其中不止有5个5,25也可以拆成5×5,因此不能单单用n / 5判断出5的个数,还得循环继续判断。

class Solution {
    public int trailingZeroes(int n) {
    	int cnt = 0;
    	while(n != 0) {
    		cnt += n / 5;
    		n /= 5;
    	}
    	return cnt;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值