leetcode-数学题-172


/**
 * <p>给定一个整数 <code>n</code> ,返回 <code>n!</code> 结果中尾随零的数量。</p>
 *
 * <p>提示&nbsp;<code>n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1</code></p>
 *
 * <p>&nbsp;</p>
 *
 * <p><strong>示例 1:</strong></p>
 *
 * <pre>
 * <strong>输入:</strong>n = 3
 * <strong>输出:</strong>0
 * <strong>解释:</strong>3! = 6 ,不含尾随 0
 * </pre>
 *
 * <p><strong>示例 2:</strong></p>
 *
 * <pre>
 * <strong>输入:</strong>n = 5
 * <strong>输出:</strong>1
 * <strong>解释:</strong>5! = 120 ,有一个尾随 0
 * </pre>
 *
 * <p><strong>示例 3:</strong></p>
 *
 * <pre>
 * <strong>输入:</strong>n = 0
 * <strong>输出:</strong>0
 * </pre>
 *
 * <p>&nbsp;</p>
 *
 * <p><strong>提示:</strong></p>
 *
 * <ul>
 * <li><code>0 &lt;= n &lt;= 10<sup>4</sup></code></li>
 * </ul>
 *
 * <p>&nbsp;</p>
 *
 * <p><b>进阶:</b>你可以设计并实现对数时间复杂度的算法来解决此问题吗?</p>
 * <div><div>Related Topics</div><div><li>数学</li></div></div><br><div><li>👍 692</li><li>👎 0</li></div>
 */

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int trailingZeroes(int n) {
        int divisor = 5;
        int res = 0;


        //不知道该咋说,有几个因子5就有几个0 

        /**
         * 现在,问题转化为:n! 最多可以分解出多少个因⼦ 5? 难点在于像 25,50,125 这样的数,可以提供不⽌⼀个因⼦ 5,怎么才能不漏掉呢? 这样,我们假设 n = 125,来算⼀算 125! 的结果末尾有⼏个 0: ⾸先,125 / 5 = 25,这⼀步就是计算有多少个像 5,15,20,25 这些 5 的倍数,它们⼀定可以提供⼀个因 ⼦ 5。 但是,这些⾜够吗?刚才说了,像 25,50,75 这些 25 的倍数,可以提供两个因⼦ 5,那么我们再计算出
         * 125! 中有 125 / 25 = 5 个 25 的倍数,它们每⼈可以额外再提供⼀个因⼦ 5。 够了吗?我们发现 125 = 5 x 5 x 5,像 125,250 这些 125 的倍数,可以提供 3 个因⼦ 5,那么我们还得再计 算出 125! 中有 125 / 125 = 1 个 125 的倍数,它还可以额外再提供⼀个因⼦ 5。 这下应该够了,125! 最多可以分解出 25 + 5 + 1 = 31 个因⼦ 5,也就是说阶乘结果的末尾有 31 个 0。
         */
        while (divisor <= n) {
            res += n / divisor;
            divisor *= 5;
        }
        return res;

    }
}
//leetcode submit region end(Prohibit modification and deletion)

posted @ 2022-08-01 11:36  小傻孩丶儿  阅读(22)  评论(0编辑  收藏  举报