您的位置:首页 > 大数据 > 人工智能

[172] Factorial Trailing Zeroes

2016-07-22 10:48 357 查看

1. 题目描述

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

Note: Your solution should be in logarithmic time complexity.

给定一个整数n,求n!中有多少个0。

2. 解题思路

n! = 1*2*….*n-1*n,题目要求求一个数的阶乘中有多少0,但是真的需要老老实实的把从1乘到n之后再数才能得出n的阶乘中0的个数嘛?显然不是的。要得到一个0,那么可能的值就是2^n*(5*m),当m=1-4时,可以得到1个0,如15*4=60,m=5时可以得到两个0,如25*8=100,依次类推,m=5^k时,可以得到k个0。

3. Code

public class Solution {
public int trailingZeroes(int n) {
// 2*5 10 4*15 20 8*25 30 ... 100
int result = 0;
while(n >= 5)
{
// 30的阶乘有7个0,5,10,15,20,25(2),30
result += (int)(n/5);
n/=5;
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 数学计算