172. 阶乘后的零

80 阅读1分钟

题目

image.png

思路

  • 要找因子中出现了几对<2,5>,由于因子2的数量总是比因子5要多,所以找因子中5出现的次数就行了。所以,每次x%5=0,count++
  • 但是有的数字存在一个以上的因子。例如,若 n = 25,那么我们只做了 count += 1。但是我们应该 count += 2,因为25有两个因子 5。
  • 所以使用while而不是if语句,若有因子5就将数字除以5。如果还有剩余的因子5,则重复步骤。

代码

class Solution {
    public int trailingZeroes(int n) {
        int count = 0;
        for (int i = 5; i <= n; i += 5) {
            int cur = i;
            while (cur % 5 == 0) {//25->5->1
                count++;
                cur /= 5;
            }
        }
        return count;
    }
}