美文网首页
[String]172. Factorial Trailing

[String]172. Factorial Trailing

作者: Reflection_ | 来源:发表于2017-10-25 14:19 被阅读0次

    题目: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;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:[String]172. Factorial Trailing

          本文链接:https://www.haomeiwen.com/subject/mhyqpxtx.html