★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-whquyqge-md.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given an integer n, return the number of trailing zeroes in n!.git
Example 1:github
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.微信
給定一個整數 n,返回 n! 結果尾數中零的數量。spa
示例 1:code
輸入: 3 輸出: 0 解釋: 3! = 6, 尾數中沒有零。
示例 2:htm
輸入: 5 輸出: 1 解釋: 5! = 120, 尾數中有 1 個零.
說明: 你算法的時間複雜度應爲 O(log n) 。blog
1 class Solution { 2 func trailingZeroes(_ n: Int) -> Int { 3 //該數應爲x*10k 的形式等於x*(2k *5k) 4 //即求該數分解質因子後有幾個5 5 var num = n 6 var sum:Int = 0 7 while(num > 0) 8 { 9 num /= 5 10 sum += num 11 } 12 return sum 13 } 14 }
16msget
1 class Solution { 2 func f1(_ n: Int) -> Int { 3 if n == 0 { 4 return 0 5 } 6 7 var all_cnt = 0 8 for i in 1...n { 9 var num = i 10 var cnt = 0 11 while num % 5 == 0 { 12 num /= 5 13 cnt += 1 14 } 15 if (cnt > 0) { 16 print(i, cnt) 17 } 18 all_cnt += cnt 19 } 20 return all_cnt 21 } 22 23 func f(_ n: Int) -> Int { 24 var factor = 5 25 var all_times = 0 26 while factor <= n { 27 var times = n / factor 28 all_times += times 29 factor *= 5 30 } 31 32 return all_times 33 } 34 35 func trailingZeroes(_ n: Int) -> Int { 36 37 return f(n) 38 } 39 }
12ms
1 class Solution { 2 func trailingZeroes(_ n: Int) -> Int { 3 if n == 0 { 4 return 0 5 } 6 7 return (n / 5) + trailingZeroes(n / 5) 8 } 9 }