172. Factorial Trailing Zeroes

题目描述:给定一个整数n,返回n!(n的阶乘)数字中的后缀0的个数。

方法一:sum可能会溢出

int trailingZeroes(int n) {
    int sum = 1;
    for (int i = 1; i <= n; i++) {
        sum *= i;
    }

    int count = 0;
    while ((sum % 10) == 0) {
        sum /= 10;
        count++;
    }
    return count;
}

方法二:解决了第一版中的溢出问题

int trailingZeroes(int n) {
    int count2 = 0;
    int count5 = 0;

    for (int i = 1; i <= n; i++) {
        int j = i;
        while (j != 0 && j % 2 == 0) {
            j /= 2;
            count2++;
        }
        j = i;
        while (j != 0 && j % 5 == 0) {
            j /= 5;
            count5++;
        }
    }

    return count2 < count5 ? count2 : count5;
}

方法三:这个版本我是百度的,请点这儿,好好看一下数学原理解释

int trailingZeroes(int n) {
    int count = 0;

    while (n != 0) {
        count += n / 5;
        n /= 5;
    }

    return count;
}

你可能感兴趣的:(172. Factorial Trailing Zeroes)