您的位置:首页 > 大数据 > 人工智能

【Leetcode】 Factorial Trailing Zeroes #172

2015-07-26 06:27 567 查看
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.

求末尾0的个数,即为求各factor中5的个数,因为每有一个5必有一个2与之组成10。其中factor 5^n 应被计算n次,因为其贡献了n个5.

5的倍数有:a = n/5

则25的倍数有:b = a/5

125的倍数有:c=b/5

....

 根据此思路,得:

class Solution {
public:
int trailingZeroes(int n) {
int number_of_trailing_zero = 0;

int num_of_5 = n/5;
while(num_of_5 != 0) {
number_of_trailing_zero += num_of_5;
num_of_5 /= 5;
}
return number_of_trailing_zero;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: