LeetCode(172):阶乘后的零 Factorial Trailing Zeroes(Java)

234 篇文章 1 订阅
177 篇文章 0 订阅

2019.9.5 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

这道题可以用一行代码直接搞定:

return (n/5)+(n/25)+(n/125)+(n/625)+(n/3125)+(n/15625)+(n/78125)+(n/390625)+(n/1953125)+(n/9765625)+(n/48828125)+(n/244140625)+(n/1220703125);

为什么呢?观察发现,阶乘数中每包含m个5n的倍数,结果就会多出m*n个0。那么结果运算只要迭代找出有多少个5n的因子即可。


传送门:阶乘后的零

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

给定一个整数 n,返回 n! 结果尾数中零的数量。

示例 1:
输入: 3
输出: 0
解释: 3! = 6, 尾数中没有零。

示例 2:
输入: 5
输出: 1
解释: 5! = 120, 尾数中有 1 个零.

说明: 你算法的时间复杂度应为 O(log n) 。


/**
 *
 * Given an integer n, return the number of trailing zeroes in n!.
 * 给定一个整数 n,返回 n! 结果尾数中零的数量。
 *
 */

public class FactorialTrailingZeroes {
    public int trailingZeroes(int n) {
        int result = 0;
        while(n >= 5){
            result += n / 5;
            n /= 5;
        }
        return result;
    }
}




#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值