137.Factorial Trailing Zeroes
阿新 • • 發佈:2018-09-05
clas pre 數量 返回 com += xpl ger integer
題目:
Given an integer n, return the number of trailing zeroes in n!.
給定一個整數n,返回n!中的尾隨零數。
Example 1:
Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero.
Note: Your solution should be in logarithmic time complexity.
註意:您的解決方案應該是對數時間復雜度。
解答:
1 class Solution { 2 public int trailingZeroes(int n) { 3 int res=0; 4 while(n>0){ 5 res+=n/5; 6 n/=5; 7 } 8 return res; 9 } 10 }
詳解:
求階乘末尾0的個數,即找乘數中10的個數,而10=2*5,2的數量>>5的數量,故找出5的個數即可。25=5*5,有兩個5,也應該考慮。
n!後綴0的個數 = n!質因子中5的個數 = floor(n/5) + floor(n/25) + floor(n/125) + ....
137.Factorial Trailing Zeroes