leetcode:Factorial Trailing Zeroes



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

Note: Your solution should be in logarithmic time complexity.

class Solution {
public:
    int trailingZeroes(int n) {
        int cnt = 0;
        /*long long i = 5;//之前一直TLE 是因爲把i的類型定義成整型,這樣當n爲整型最大值時,i乘以5將會超出整型範圍變成負數,這樣n除以i將不會爲0而陷入死                          //循環,後來發現其實i的定義純屬多餘,以後一定要注意細節
        while(n / i)
        {
           cnt += n / i;
           i *= 5;
        }*/
        while(n)
        {
            cnt += n / 5;
            n /= 5;
        }
        return cnt;
    }
};

發佈了101 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章