172. Factorial Trailing Zeroes

来源:互联网 发布:北航软件工程硕士学费 编辑:程序博客网 时间:2024/05/11 09:03

头一次遇上翻译完了还没看懂意思的题目,英文功底还是需要的啊=__=||
描述:
Given an integer n, return the number of trailing zeroes in n!.

就这么一句话,意思是这样:给出一个整数,int型,计算以这个整数开始的阶乘n!,这个阶乘得到的数中的尾部有多少个0.

我们可以知道10 = 2*5,也就是说从1到n中:一个尾数为5和一个尾数为2的数乘起来就有1个0。当然,分解开来还是5*2。
以10为例子:1 2 3 4 5 6 7 8 9 10 ,包含2和为2的数有多少个稍微瞟一眼就能知道了,总之很多;;而5呢?只有5和10 = 5×2总共2个。
这就不用说了,2本来的就能被大多数整除,那要找和5匹配的2是一抓一大把,那么这里我们得出一个结论:只需要找其中所有能被5整数的数,求得每一个数能被分解成多少个5的总数。

开始的代码是这样:

class Solution {public:    int trailingZeroes(int n) {        if(n < 4){return 0;}        int time = 0;        while(n/5 != 0){            n /= 5;            time += n;        }        return time;    }};

计算5的个数, SUM = N/5^1+N/5^2 +N/5^3+….

改进之后的代码:

class Solution {public:    int trailingZeroes(int n) {       return n==0?0:n/5 + trailingZeroes(n/5);        }};

对于python有更多一种方法,因为python支持自动将低长度的数字自动转换成大数
同上的方法:

class Solution(object):    def trailingZeroes(self, n):        return (0 if n == 0 else (n/5+self.trailingZeroes(n/5)))

另外一种乘的方法:

class Solution(object):    def trailingZeroes(self, n):        time = 0         x = 5        while n >= x:            time += n/x            x *= 5    #在c++中使用这样乘,很快就使得x超出int型的长度了,出错,所以不能使用        return time

特别注意:Python会自动把大数转化为long类型,足够应付比较大的输入。
这里写图片描述

0 0
原创粉丝点击