C#LeetCode刷題之#172-階乘後的零(Factorial Trailing Zeroes)
阿新 • • 發佈:2018-12-12
問題
給定一個整數 n,返回 n! 結果尾數中零的數量。
輸入: 3
輸出: 0
解釋: 3! = 6, 尾數中沒有零。
輸入: 5
輸出: 1
解釋: 5! = 120, 尾數中有 1 個零.
說明: 你演算法的時間複雜度應為 O(log n) 。
Given an integer n, return the number of trailing zeroes in n!.
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Note: Your solution should be in logarithmic time complexity.
示例
public class Program { public static void Main(string[] args) { var n = 18; var res = TrailingZeroes(n); Console.WriteLine(res); Console.ReadKey(); } private static int TrailingZeroes(int n) { //統計包含因子5的數量即可 var res = 0; while(n > 1) { res += (n /= 5); } return res; } }
以上給出1種演算法實現,以下是這個案例的輸出結果:
3
分析:
顯而易見,以上演算法的時間複雜度為: 。