leetcode——172 Factorial Trailing Zeroes(N!尾巴上有多少個0,演算法複雜度為lg),leetcodefactorial

來源:互聯網
上載者:User

leetcode——172 Factorial Trailing Zeroes(N!尾巴上有多少個0,演算法複雜度為lg),leetcodefactorial
Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.(您的解決方案應該在對數時間複雜度。)

Hide Tags: Math


題目要求:給定N,求N!的末尾有多少0。要求演算法複雜度為lg

解題思路:

思路一:

想的比較簡單,先實用for迴圈進行階乘運算,然後mod10計算0的個數,但是在OJ檢查時,逾時!,顯然是沒滿足演算法時間複雜度為lg的要求。(失敗)

代碼如下:

public static int trailingZeroes1(int n){int sum=1;int count=0;for (int i = n; i >0; i--){sum*=i;}while (sum!=0){int remain=sum%10;if (remain==0){count++;}else if (remain!=0){break;}sum/=10;}return count;}

思路二(推薦):

只有在2*5的時候才會出現0,其中整十的數也可以看成是2*5的結果,因此,只要在n之間看有多個2,多少個5即可,不難發現2的個數大於5的個數。


因此只需要要記錄5的個數即可。但是需要注意的是:像25,125,625之類的數,除以5以後的結果還是5的倍數,所以還需要繼續迴圈處理。


(OJ測試成功)

代碼如下:

public static int trailingZeroes(int n){int result=0;while (n!=0){result=result+n/5;n/=5;}return result;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.