Java 計算N階乘末尾0的個數-LeetCode 172 Factorial Trailing Zeroes

來源:互聯網
上載者:User

標籤:

題目

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

Note: Your solution should be in logarithmic time complexity.

分析

Note中提示讓用對數的時間複雜度求解,那麼如果粗暴的算出N的階乘然後看末尾0的個數是不可能的。

所以仔細分析,N! = 1 * 2 * 3 * ... * N 而末尾0的個數只與這些乘數中5和2的個數有關,因為每出現一對5和2就會產生一個10那麼N!末尾一定會有一個0。然而進一步分析會發現,因子中2的個數肯定是大於5的個數,所以我們只要找出N!中因子5的總個數即可。

1.給定N那麼N/5會得到所有5*1, 5*2, 5*3......的個數

2.N/25會得到所有25*1, 25*2, 25*3.....的個數

3.N/125會得到所有125*1, 125*2, 125*3.......的個數

........

可能會有疑問,25中有兩個5,125中有3個5會不會少算,但是仔細觀察會發現,在第1步中已經對25的情況算了一次,第2步相當於把另一個5統計進來,以此類推

代碼
1     public int trailingZeroes(int n) {2         int rs = 0;3         while (n != 0) {4             rs += (n / 5);5             n /= 5;6         }7         return rs;8     }

這樣就得出了結果

 

Java 計算N階乘末尾0的個數-LeetCode 172 Factorial Trailing Zeroes

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.