Factorial Trailing Zeroes
Total
Accepted: 44351 Total
Submissions: 144160 Difficulty: Easy
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
思路:1).n!=n*(n-1)*(n-2)*...*2*1,只有當因子有2,5的時候,在n!的末尾纔會產生10.
2).因爲5>2,無論n爲多大,在n!當中,5的數量肯定比2少。所以,我們只需要計算n!有多少個因子5就行了。
3).循環體可以這麼理解,第一次循環,有幾個5的倍數,第二次循環,有幾個25的倍數..第m次循環,有幾個5^m的倍數。直到n<5^m。
class Solution {
public:
int trailingZeroes(int n) {
int sum = 0;
while(n>0){
sum+=n/5;
n/=5;
}
return sum;
}
};