首页 > 代码库 > leetcode 172: Factorial Trailing Zeroes

leetcode 172: Factorial Trailing Zeroes

Factorial Trailing Zeroes

Total Accepted: 28 Total Submissions: 69

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in polynomial time complexity.

[分析]

分解因子, 当且仅当 因子中出现 一对 (2,5)时, 最后结果会增加一个 trailing zero.

[注意事项]

[CODE]

public class Solution {
    public int trailingZeroes(int n) {
        if(n<1) return 0;
        long c2 = 0;
        long c5 = 0;
        for(int i=n; i>1; i--) {
            int k = i;
            while(k%5==0) { k/=5; ++c5;}
            while(k%2==0) { k/=2; ++c2;}
        }
        return (int)Math.min(c2, c5);
    }
}



leetcode 172: Factorial Trailing Zeroes