Factorial Trailing Zeroes

来源:互联网 发布:linux 服务器版本 编辑:程序博客网 时间:2024/06/09 23:00

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

Note: Your solution should be in logarithmic time complexity.

方法:求乘积中5的个数。

class Solution {public:    int trailingZeroes(int n) {        long num5 = 0; //int overflow        long base = 5;        while(n/base){           num5 += n/base;          base *= 5;        }        return num5;    }};

切忌不可用int类型定义,容易溢出。
防止溢出可以换种编程方式进行。

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