[leetcode] 172. Factorial Trailing Zeroes

来源:互联网 发布:卓易云软件下载 编辑:程序博客网 时间:2024/06/15 11:02

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.


这道题是求阶乘结果尾部0的个数,题目难度为Easy。

尾部的0都是由5乘以偶数得来的,也就是说n!中每有一个因子5,尾部就会有一个0,而5的乘方要当做多个5(5本身除外)来处理,因为它有多个因子5,这样问题就转化为统计n!中一共有多少因子5,处理起来就比较简单了,具体代码:

class Solution {public:    int trailingZeroes(int n) {        int ret = 0;        while(n) {            n /= 5;            ret += n;        }        return ret;    }};

0 0
原创粉丝点击