【Leetcode】 Factorial Trailing Zeroes #172

来源:互联网 发布:日本聊天软件排名 编辑:程序博客网 时间:2024/06/05 19:45
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;    }};


0 0
原创粉丝点击