1. 程式人生 > >LeetCode 172. Factorial Trailing Zeroes

LeetCode 172. Factorial Trailing Zeroes

AC BE color tco div lee style 但是 ...

Given an integer n, return the number of trailing zeroes in n!.

思路:

階乘末尾有多少零,取決於結果中有多少個10。而又多少個10又取決於結果中有多少個5(2的數量是遠大於5的,因此數5的數量即可)。

數5的個數直接n/5即可,但是要註意25,125等特殊情況,需要將額外的5計算進來。這些情況計算n/5^2, n/5^3, ...

類似數學題做過一遍基本就會了。

class Solution {
public:
    int trailingZeroes(int n) {
        int count=0;
        
while (n>0){ count += n/5; n = n/5; } return count; } };

LeetCode 172. Factorial Trailing Zeroes