leetcode - Factorial Trailing Zeroes

leetcode - Factorial Trailing Zeroes

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

Note: Your solution should be in logarithmic time complexity.

要求对数复杂度。

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

没想到这个解法,虽然想到了只需数5的个数。

本质上就是看乘数里面有多少个因子5. 所有的因子5都会和偶数相乘得到一个0;

原数除以5得到的因子5的个数,但是25里面有两个因子5,所以原数除以5后再计算一遍,直到数字为0。

或者说,计算的是5的个数+25的个数(包括两个5)+125的个数(包括3个5)+。。。

 

具体分析:http://www.cnblogs.com/ganganloveu/p/4193373.html

 

posted @ 2015-05-13 13:20  cnblogshnj  阅读(93)  评论(0编辑  收藏  举报