首页 > 其他 > 详细

leetcode Factorial Trailing Zeroes

时间:2015-11-29 16:17:27      阅读:246      评论:0      收藏:0      [点我收藏+]

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

Note: Your solution should be in logarithmic time complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

 

Subscribe to see which companies asked this question

 
这种题就是找规律,对我来说就是这样;刚开始想简单了认为判断(n*n-1)%10==0如果是就加1,这明显6!都不符合。
后来发现基本上就是遇5加1,但是100也不符合,100有20个5,期待值却是24;这4是什么呢,后来发现是有4个25;
所以其实是5进制的感觉,虽然最终没有找到规律。就像25有5个5,但是期待值是6,所以就是遇5进1;
 
所以最后我是用了一个循环,先求log(5)n,例如log(5)100=2.8几的,取2;于是只要看5的1次方和5的2次方,即有几个5,有几个25.
假如是1000的话,log(5)1000=4.29,取4,所以看5,25,125,625,看1000分别有几个5,几个25,几个125,几个625.
 
我发现这种和期待值对比的方法,,,容易让人找规律,不过这道题总结起来就是遇5加1!
C++中求对数的方法:n=log(a)b   也就是n=log(b)/log(a)  
 
 
 1 class Solution {
 2 public:
 3     int trailingZeroes(int n) {
 4         int m=0,result=0;
 5         int count=log(n)/log(5);
 6         for(int i=1;i<=count;i++){
 7             m=pow(5,i);
 8             result+=n/m;
 9         }
10         return result;
11 
12         }
13 };

 

leetcode Factorial Trailing Zeroes

原文:http://www.cnblogs.com/LUO77/p/5004837.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!