LeetCode 172: Factorial Trailing Zeroes

題目鏈接:

https://leetcode.com/problems/factorial-trailing-zeroes/description/

描述

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

Note: Your solution should be in logarithmic time complexity.

算法思想:

組合數學中的題目。
因爲所有尾隨0都來自因子5 * 2。
但有時一個數字可能有幾個5個因數,例如25個有5個因子,125個有5個因子。 在n! 操作,因數2的個數永遠比5多。 所以我們只計算從1到n的所有數字中的5個因素。

源代碼

/*
Author:楊林峯
Date:2017.12.30
LeetCode(172):三點順序
*/
class Solution {
public:
    int trailingZeroes(int n) {
        int ans = 0;
        while(n)
        {
            ans += n/5;
            n /= 5;
        }
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章