Leetcode - Factorial Trailing Zeroes

[思路]
数乘积结果的后缀0,其实就是数结果中有多少个因子10,10=2*5,易知因子2是充裕的,因此只要数因子5的个数,暴力的方法是统计并加和1到n每个数含有因子5的个数,会超时。
能贡献因子5的数是5,10,15,20,25,30……,其中所有5的倍数会至少贡献1个因子5,所有25的倍数会至少贡献两个因子5,所有5*5*5=125的倍数会至少贡献三个因子5,依次类推,因此n中5的因子个数=n/5 + n/25 + n/125……,实现时写成循环即可。
实现这个思路没有一次bug free,忽视了溢出问题,再次强调 涉及整数运算是要牢记处理运算溢出问题,省事的方案就是使用long类型

public class Solution {
    public int trailingZeroes(int n) {
        int count5 = 0;
        long num = n;
        long divd = 5;
        long times = n / divd;
        while (times > 0) {
            count5 += times;
            divd *= 5;
            times = n / divd;
        }
        return count5;
    }
}

猜你喜欢

转载自likesky3.iteye.com/blog/2237771
今日推荐