Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
求階乘的后綴0個(gè)數(shù)乘法中的零來源于10,10來源于2和5,在階乘中,1個(gè)數(shù)的質(zhì)因子出現(xiàn)1次5,那末必定有其他數(shù)的質(zhì)因子出現(xiàn)若干次2
所以問題變成求解質(zhì)因子5出現(xiàn)的次數(shù),
n/5求出包括1個(gè)5的數(shù)字個(gè)數(shù)
n/25求出包括兩個(gè)5的數(shù)字個(gè)數(shù)...以此類推
class Solution { public: int trailingZeroes(int n) { int res = 0; while(n) { res += n/5; n/=5; } return res; } };
上一篇 樸素貝葉斯