leetcode刷題--Factorial Trailing Zeroes
題目:求一個整數階乘後數字字尾中0的個數。要求解法滿足多項式時間複雜度。
最容易想到的是先求階乘再處理字尾,有程式碼:
class Solution:
# @param {integer} n
# @return {integer}
def trailingZeroes(self, n):
result=1
i=0
while(i<n):
result*=(n-i)
i+=1
for i in [str(j) for j in range(1,10)]:
return min([str(result).rfind(i) for i in [str(j) for j in range(1,10)]])-1
然而不能通過,因為時間上不滿足要求
那想辦法解決,容易想到,10=2*5,所以如果得出n的階乘由幾對2*5得到即可,我們判斷小於n的數中有幾對2*5,但容易發現。。。5總是比2少,因此只找含5的即可。也就是說找到小於n的5的冪即可。
程式碼:
class Solution: # @param {integer} n # @return {integer} def trailingZeroes(self, n): x = 5 result = 0 while n >= x: result += int(n / x) x *= 5 return result
相關文章
- Leetcode 172. Factorial Trailing ZeroesLeetCodeAI
- Factorial Trailing Zeroes 階乘後的零AI
- 每天一道LeetCode--172. Factorial Trailing ZeroesLeetCodeAI
- [CareerCup] 17.3 Factorial Trailing Zeros 求階乘末尾零的個數AIROS
- LeetCode—283—Move ZeroesLeetCode
- Leetcode Set Matrix ZeroesLeetCode
- LeetCode 73 Set Matrix ZeroesLeetCode
- Leetcode-Set Matrix ZeroesLeetCode
- Set Matrix Zeroes leetcode javaLeetCodeJava
- LeetCode刷題整理LeetCode
- leetcode刷題(一)LeetCode
- LeetCode刷題 堆LeetCode
- LeetCode 刷題—樹LeetCode
- Leetcode 73. Set Matrix ZeroesLeetCode
- LeetCode 刷題指南(一):為什麼要刷題LeetCode
- LeetCode 刷題筆記LeetCode筆記
- leetcode刷題筆記LeetCode筆記
- LeetCode刷題記錄LeetCode
- 如何使用leetcode刷題LeetCode
- leetcode刷題--Majority ElementLeetCode
- leetcode刷題--Count PrimesLeetCode
- leetcode刷題--Reverse BitsLeetCode
- leetcode刷題--Rotate ArrayLeetCode
- leetcode刷題--Count and SayLeetCode
- Leetcode刷題分類LeetCode
- Leetcode刷題準備LeetCode
- LeetCode刷題—陣列LeetCode陣列
- 283. Move Zeroes--LeetCode RecordLeetCode
- Leetcode刷題——求眾數LeetCode
- leetcode刷題筆記605LeetCode筆記
- Leetcode刷題系列彙總LeetCode
- leetcode刷題--Happy NumberLeetCodeAPP
- leetcode刷題--Number of 1 BitsLeetCode
- leetcode刷題記錄 661~LeetCode
- LeetCode刷題之第701題LeetCode
- Leetcode已刷題目題解彙總LeetCode
- leetcode排序專題演算法刷題LeetCode排序演算法
- 用Rust刷leetcode第十題RustLeetCode