MENU

LeetCode172. 阶乘后的零

July 9, 2018 • Read: 2516 • LeetCode阅读设置

要求末尾有多少个零,则该数应为$x\times 10^k$ 的形式等于$x\times (2^k\times 5^k)$在阶乘里,2的数量远大于5,所以我们只用统计有多少个5就行,对于一个数的阶乘,例如6,1*2*3*4*5*6 = 1*2*3*2*2*5*6,因数中有一个5,所以答案就是1

class Solution {
    public int trailingZeroes(int n) {
        int ans = 0;
        while(n > 0) {
            ans += n / 5;
            n /= 5;
        }
        return ans;
    }
}
Last Modified: May 12, 2021
Archives Tip
QR Code for this page
Tipping QR Code