首页 > 代码库 > LeetCode 172 Factorial Trailing Zeroes

LeetCode 172 Factorial Trailing Zeroes

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

Note: Your solution should be in logarithmic time complexity.

 

思路:

首先末尾0的个数取决于素因数中2和5个数较少者,其次5的个数要远远小于2的个数,因此返回素因数中5的个数即可。有公式[n/5] + [n/25] + [n/125] + ... + [n/5x]

 

解法:

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

 

LeetCode 172 Factorial Trailing Zeroes