Leetcode NO.172 Factorial Trailing Zeroes

来源:互联网 发布:当红网络歌曲 编辑:程序博客网 时间:2024/06/05 02:25

本题题目要求如下:

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

Note: Your solution should be in logarithmic time complexity.

应该说这算是leetcode里面最简单的一道题了。。基本就是我天朝小学数学的水平。。。。

数多少个0其实本质上就是数有多少个2 * 5,比如10本身就贡献了2*5,像25,就贡献了2个5

而且需要注意的是,无论怎样,2肯定要比5多。。

比如1,2,3,4,5,6,7,8,9,10里面只有3个5,却有数不清的2,反正肯定大于3,所以这道题就简化为数1到n之间的数有多少个5

详细代码如下:

class Solution {public:    int trailingZeroes(int n) {        /* count the number of 5 */        int cnt = 0;        while (n/5 >= 1) {            n /= 5;            cnt += n;        }        return cnt;    }};



0 0
原创粉丝点击