[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.

思路:

 求n的阶乘最后面连续的0的个数,且时间复杂度在log(n)
 直接思路:
 求n的阶乘,记为sum,然后对10取余,若为0则计数+1,否则退出
 计数即为末位0的个数
 但是只能计算到12的阶乘,13及以后的阶乘就会int溢出,出现错误,而且时间复杂度巨高

 修改思路:
 只有2和5相乘的时候,末位才会出现0.所以只要统计阶乘中出现2和5的个数即可。
 n = 5: 5!的质因子中 (2 * 2 * 2 * 3 * 5)包含一个5和三个2。因而后缀0的个数是1。
 n = 11: 11!的质因子中(2^8 * 3^4 * 5^2 * 7)包含两个5和三个2。于是后缀0的个数就是2。
 由实际情况很容易发现,阶乘中2出现的次数远远大于5出现的次数。所以只要统计5出现的次数即可
 递归求n/5的个数即可
 n/5可知n里面包含几个5,而5的幂次里包含多个5 如25有2个5,125有3个5
 计算5的个数时, 最简单的方法是 SUM(N/5^1, N/5^2, N/5^3...)

 1 public class Solution172 {
 2     public int trailingZeroes(int n) {
 3         //直接思路
 4     /*    int count=0;
 5         int sum = 1;
 6         for(int i = n; i>0;i--){
 7             sum = sum * i;
 8         }
 9         while(sum%10 == 0){
10             sum = sum/10;
11             count++;
12         }
13         return count;
14         */
15         int count = 0;
16         while(n>0){
17             count += n/5;
18             n = n/5;
19         }
20         return count;
21     }
22 
23     public static void main(String[] args) {
24         // TODO Auto-generated method stub
25         Solution172 solution172 = new Solution172();
26         int n = 13;
27         System.out.println(solution172.trailingZeroes(n));
28     }
29 
30 }

 

posted @ 2018-01-04 17:38  zlz099  阅读(97)  评论(0编辑  收藏  举报