输入: 3 输出: 0 解释: 3! = 6, 尾数中没有零。 输入: 5 输出: 1 解释: 5! = 120, 尾数中有 1 个零. 复制代码
思考:
直接的想法是先求n的阶乘,再求结果末尾的0个数。但是n的阶乘值很容易就会出现超出范围的现象,所以之歌方法不可行。 再思考: 1!= 1 2! = 1 * 2 = 2 3! = 1 * 2 * 3 = 6 4! = 1 * 2 * 3 * 4 = 24 5! = 1 * 2 * 3 * 4 * 5 = 120 思考末尾的0从哪里来的?末尾零是由2*5得来。 可以把n的阶乘全部拆成质数因子相乘,最终所有因子中的2肯定比5出现的多,因为2,4,6,8,10其中都有2,而5只有,5,10,15,20,25中才有。 所以有多少个5最终末尾就会有多少个0. 复制代码
实现:
class Solution {
public int trailingZeroes(int n) {
int count = 0;
while(n >= 5) {
count += n / 5;
n /= 5;
}
return count;
}
}复制代码
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
具体数学(英文版第2版)
[美] Ronald L. Graham、Donald E. Knuth、Oren Patashnik / 机械工业出版社 / 2002-8 / 49.00元
This book introduces the mathematics that supports advanced computer Programming and the analysis of algorithms. The primary aim of its well-known authors is to provide a solid and relevant base of ma......一起来看看 《具体数学(英文版第2版)》 这本书的介绍吧!