[CareerCup] 17.3 Factorial Trailing Zeros 求階乘末尾零的個數

Grandyang發表於2016-04-20

 

LeetCode上的原題,講解請參見我之前的部落格Factorial Trailing Zeroes

 

解法一:

int trailing_zeros(int n) {
    int res = 0;
    while (n) {
        res += n / 5;
        n /= 5;
    }
    return res;
}

 

解法二:

int trailing_zeros(int n) {
    return n == 0 ? 0 : n / 5 + trailing_zeros(n / 5);
}

 

CareerCup All in One 題目彙總

相關文章