描述
給定一個整數n,返回n!(n的階乘)的尾隨零的個數。
您的解法時間複雜度應爲對數級別。
思路
由於2和5可以形成0,且2的個數總是多於5,所以尾部0的個數是由0~n中包含5的個數決定的。譬如,5包含1個5,10包含1個5,25包含兩個5…
#ifndef C1347_H
#define C1347_H
#include<iostream>
using namespace std;
class Solution {
public:
/**
* @param n: a integer
* @return: return a integer
*/
int trailingZeroes(int n) {
// write your code here
int cnt = 0;
//由於2和5可以形成0,且2的個數總是多於5,即找0~n中的數包含5的個數
while (n != 0)
{
cnt += n / 5;
n = n / 5;
}
return cnt;
}
};
#endif