2019.9.5 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
这道题可以用一行代码直接搞定:
return (n/5)+(n/25)+(n/125)+(n/625)+(n/3125)+(n/15625)+(n/78125)+(n/390625)+(n/1953125)+(n/9765625)+(n/48828125)+(n/244140625)+(n/1220703125);
为什么呢?观察发现,阶乘数中每包含m个5n的倍数,结果就会多出m*n个0。那么结果运算只要迭代找出有多少个5n的因子即可。
Given an integer n, return the number of trailing zeroes in n!.
给定一个整数 n,返回 n! 结果尾数中零的数量。
示例 1:
输入: 3
输出: 0
解释: 3! = 6, 尾数中没有零。
示例 2:
输入: 5
输出: 1
解释: 5! = 120, 尾数中有 1 个零.
说明: 你算法的时间复杂度应为 O(log n) 。
/**
*
* Given an integer n, return the number of trailing zeroes in n!.
* 给定一个整数 n,返回 n! 结果尾数中零的数量。
*
*/
public class FactorialTrailingZeroes {
public int trailingZeroes(int n) {
int result = 0;
while(n >= 5){
result += n / 5;
n /= 5;
}
return result;
}
}
#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#