[LeetCode 172] Factorial Trailing Zeroes

  • 2 * 5可以的到一个10
  • 2的个数远比5的个数要多,所以我们需要计算出n!中有几个5
  • 从1开始算,每5个数会出现一个因子5 (n/5进行计算)
  • 从1开始算,每25个数会多出现一个因子5 (n/25进行计算)
  • ...

Implementation

public class Solution {
    public int trailingZeroes(int n) {
        int count = 0;
        for (int i = 5; n / i > 0; i = i * 5) {
            count += n / i;
        }
        return count;
    }
}
  • i*5可能会发生overflow,因此应该用下面这种办法
public class Solution {
    public int trailingZeroes(int n) {
        int count = 0;
        while (n > 0) {
            count += n / 5;
            n /= 5;
        }
        return count;
    }
}
posted @ 2016-02-15 08:12  VicHawk  阅读(102)  评论(0编辑  收藏  举报