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

172 Factorial Trailing Zeroes

2016-01-31 15:35 417 查看
题目链接:https://leetcode.com/problems/factorial-trailing-zeroes/

题目:

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

Note: Your solution should be in logarithmic time complexity.


解题思路:

这题的考点依然是数学问题。

解决办法依然是找规律。

对本题来说,只有包含 5 的倍数和 2 的倍数的数字可以产生 0.

由于 2 的倍数的数字远多于 5 的倍数,所以本质就是在 1 ~ n 的范围内找 5 的倍数,以及这些倍数本身具体包含几个 5 相乘。最终统计出一共有多少个 5,即可产生多少个 尾数0.

代码实现:

public class Solution {
public int trailingZeroes(int n) {
if(n < 0)
return -1;
int count = 0;
for(long i = 5; n / i >= 1; i *= 5) {
count += n / i;
}
return count;
}
}


502 / 502 test cases passed.
Status: Accepted
Runtime: 2 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: