Leetcode之PHP版题目解析(172. Factorial Trailing Zeroes)


2019-3-26 星期二  开始吧


今天搭了一天的office web apps,搭了一半(实在是麻烦),之前用的是office那几个第三方包来操作execl,word,ppt那些,最终还是搭一个服务吧,毕竟客户是上帝.(打算这个搭完实现在线编辑修改微软服务写一篇blog好好记录一下)


上一题链接 Leetcode之PHP版题目解析(169. Majority Element)

847f5f3d7321f63d71ee34bb694f9199.png


题目描述

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


题目分析

求一个数阶乘末尾0的个数,尾数要是等于0的话,那么必定是可以被5整除的数,如果当前是!5,就有1个被5整数的数,!10就有两个,依次类推.所以这道题也就是在求一个阶乘数里面有多少个因式分子5.

具体实现

    /**
     * @param Integer $n
     * @return Integer
     */
    function trailingZeroes($n) {
        $res=0;
        while($n){
            $res +=intval($n/5);
            $n /=5;  //分解因式分子后5的个数
        }
        return $res;
    }

解法二

这道题稍微改进一下,用递归实现可以丧心病狂的把代码压缩到一行.

    /**
     * @param Integer $n
     * @return Integer
     */
    function trailingZeroes($n) {
        return   $n==0?0:intval($n/5)+$this->trailingZeroes($n/5);
    }

运行


Github整理地址:https://github.com/wuqinqiang/leetcode-php

b995b610c9c504d90dd56c6c6ffd8792.png


Vote Vote Cancel Collect Collect Cancel

<< 上一篇: Leetcode PHP题解--D15 509. Fibonacci Number

>> 下一篇: Leetcode No.268 Missing Number(缺失数字)