LeetCode Factorial Trailing Zeroes

来源:互联网 发布:架子鼓打谱软件 编辑:程序博客网 时间:2024/05/23 11:07

思路:

求阶乘的末尾0的个数。

n的阶乘可以写成: n!=2x3y5z...
即所有质因子的乘积,只有一对2和5两个质因子相乘会贡献一个末尾0,又因为x一定大于z,所以只需计算有多少个质因子5即可。

class Solution {public:    int trailingZeroes(int n) {        int ans = 0;        while(n) {            ans += n/5;            n /= 5;        }        return ans;    }};
0 0
原创粉丝点击