137.Factorial Trailing Zeroes

题目:

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

给定一个整数n,返回n!中的尾随零数。

Example 1:

Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.

Example 2:

Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.

Note: Your solution should be in logarithmic time complexity.

注意:您的解决方案应该是对数时间复杂度。

解答:

 1 class Solution {
 2     public int trailingZeroes(int n) {
 3         int res=0;
 4         while(n>0){
 5             res+=n/5;
 6             n/=5;
 7         }
 8         return res;
 9     }
10 }

详解:

求阶乘末尾0的个数,即找乘数中10的个数,而10=2*5,2的数量>>5的数量,故找出5的个数即可。25=5*5,有两个5,也应该考虑。

n!后缀0的个数 = n!质因子中5的个数 = floor(n/5) + floor(n/25) + floor(n/125) + ....

猜你喜欢

转载自www.cnblogs.com/chanaichao/p/9588310.html