[String]172. Factorial Trailing

2017-10-25  本文已影响0人  Reflection_

题目:172. Factorial Trailing Zeroes

Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.

n!得到的数末尾有多少零。

2 * 5 = 10 带来一个0;所以只需计算n!里的25的pair。2很多(双数都可以)所以计算5得出pair数,即n/5。
然而考虑5的n次幂,以25为例,是5
5,也就是可以分别和两个2相乘得到0,所以实际要计算n/5/5...直到商为0,即不能被5整除。结果为n/5+n/5/5...之和

class Solution {
    public int trailingZeroes(int n) {
        int res = 0;
        while (n/5 !=0){
            res +=  n/5;
            n /= 5;
        }
        return res;
    }
}

上一篇下一篇

猜你喜欢

热点阅读