题目
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
思路
给出一个整数n,计算n的阶乘的结果,有多少个0
如果计算阶乘,然后再计算结果中有多少个0时,容易造成数据过大溢出;可以换个角度考虑,最后乘积结果中出现的0是2X5得到的;
考虑n=5,将数字都分解成质数时,2X3X2X2X5;
考虑n=8,将数字都分解成质数,2x3x2x2x5x2x3x7x2x2x2
考虑n=11,将数字都分解成质数时,2x3x2x2x5x2x3x7x2x2x2x3x3x2x5x11;
所以统计2和5的个数,可以计算出阶乘结果中0的个数;
计算n中包含多少个5,15有3个5(15除以5);25有6个5(20除以是4,25可以分解成两个5,所以是6个5)
所以直到除以5为0时,才能统计出5的个数
代码
public class Solution {
/**
* @param n求n的阶乘结果中有多少个0
* */
public int trailingZeroes(int n) {
int result=0;
//统计5的个数,n除以5直到为0
while(n>0){
int k=n/5;
result+=k;
n=k;
}
return result;
}
}