首页 > 其他分享 >lintcode:Trailing Zeros

lintcode:Trailing Zeros

时间:2022-12-01 19:06:35浏览次数:41  
标签:10 return sum lintcode long Zeros 100 每隔 Trailing


15:00 Start Write an algorithm which computes the number of trailing
zeros in n factorial.

Example 11! = 39916800, so the out should be 2

Challenge O(log N) time

阶乘末尾一个零表示一个进位,则相当于乘以10
而10 是由2*5所得,在1~100当中,可以产生10的有:0 2 4 5 6 8 结尾的数字,
显然2是足够的,因为4、6、8当中都含有因子2,所以都可看当是2,那么关键在于5的数量了
那么该问题的实质是要求出1~100含有多少个5
由特殊推广到一般的论证过程可得:
1、 每隔5个,会产生一个0,比如 5, 10 ,15,20.。。

2 、每隔 5×5 个会多产生出一个0,比如 25,50,75,100

3 、每隔 5×5×5 会多出一个0,比如125.

接着,请问N!的末尾有多少个零呢??

其实 也是同理的

N/5+N/25+……

class Solution {
public:
// param n : description of n
// return: description of return
long long trailingZeros(long long n) {
long long sum=0;
while(n){
sum+=n/5;
n=n/5;
}
return sum;
}
};


标签:10,return,sum,lintcode,long,Zeros,100,每隔,Trailing
From: https://blog.51cto.com/u_15899184/5903597

相关文章

  • lintcode:Update Bits
    Giventwo32-bitnumbers,NandM,andtwobitpositions,iandj.WriteamethodtosetallbitsbetweeniandjinNequaltoM(eg,Mbecomesasubstring......
  • lintcode: Fast Power
    Calculatethea^b%bwherea,bandnareall32bitintegers.ExampleFor231%3=2For1001000%1000=0ChallengeO(logn)思路参见我的博客​​幂模运算​​cla......
  • lintcode:Binary Tree Serialization
    Designanalgorithmandwritecodetoserializeanddeserializeabinarytree.Writingthetreetoafileiscalled‘serialization’andreadingbackfromthe......
  • lintcode: N-Queens
    Then-queenspuzzleistheproblemofplacingnqueensonann×nchessboardsuchthatnotwoqueensattackeachother.Givenanintegern,returnalldistincts......
  • lintcode:Permutations
    Givenalistofnumbers,returnallpossiblepermutations.ChallengeDoitwithoutrecursion.1.递归classSolution{public:/***@paramnums:Alistofi......
  • lintcode:Subsets
    Givenasetofdistinctintegers,returnallpossiblesubsets.ChallengeCanyoudoitinbothrecursivelyanditeratively?1.18sclassSolution{public:/**......
  • lintcode: Permutations II
    Givenalistofnumberswithduplicatenumberinit.Findalluniquepermutations.可以见我的博文​​全排列实现​​classSolution{public:/***@paramnu......
  • lintcode: Subsets II
    Givenalistofnumbersthatmayhasduplicatenumbers,returnallpossiblesubsets1.先排序;再按求Subsets一样的做法,只是添加前检查是否已经存在。耗时171mscla......
  • lintcode:Subarray Sum Closest
    Givenanintegerarray,findasubarraywithsumclosesttozero.Returntheindexesofthefirstnumberandlastnumber.ExampleGiven[-3,1,1,-3,5],retur......
  • lintcode: Sqrt(x)
    Implementintsqrt(intx).Computeandreturnthesquarerootofx.Examplesqrt(3)=1sqrt(4)=2sqrt(5)=2sqrt(10)=3ChallengeO(log(x))求非线性方程的解可以......