资讯专栏INFORMATION COLUMN

[LeetCode/LintCode] Factorial Trailing Zeros

Java_oldboy / 659人阅读

摘要:是的倍数,先找有多少个个,然后找多少个个,补上,然后多少个个,补上个个个

Problem

Write an algorithm which computes the number of trailing zeros in n factorial.

Challenge

11! = 39916800, so the output should be 2

Note

i是5的倍数,先找有多少个5(1个0),然后找多少个25(2个0),补上,然后多少个125(3个0),补上……

Solution
class Solution {
    public long trailingZeros(long n) {
        long i = 5;
        long count = 0;
        while (i <= n) { 
        //n = 125, i = 5, count = 25; 25个5 
        //i = 25, count += 5(5个25)= 30; i = (1个)125, count  += 1 = 31; 
            count += n / i;
            i = i * 5;
        }
        return count;
    }
}
LeetCode version
class Solution {
    public int trailingZeroes(int n) {
        int count = 0;
        while (n > 0) {
            count += n/5;
            n /= 5;
        }
        return count;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65468.html

相关文章

  • 【5 kyu】计算N的阶乘末尾几个0,Number of trailing zeros of N!

    摘要:函数可解析数字或者字符串,并返回其整数部分。其中为可选参数,默认为进制。字符串首字符为数字字符串首字符为非数字和在对负数进行取整时,结果是有差异的。 原题目 Write a program that will calculate the number of trailing zeros in a factorial of a given number. http://mathworld...

    beanlam 评论0 收藏0
  • [Leetcode] Factorial Trailing Zeroes 末尾零

    摘要:迭代法复杂度时间空间思路技巧在于,每个数会产生一个。为什么呢试想,前个数中有一个一个,相乘有一个,后个数中有一个,又有一个。以此类推,每个数会有一个。代码阶乘中有多少,结果就有多少个 Factorial Trailing Zeroes Given an integer n, return the number of trailing zeroes in n!. Note: Your ...

    qpwoeiru96 评论0 收藏0
  • [LeetCode/LintCode] Top K Frequent Words

    LeetCode version Problem Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, t...

    0x584a 评论0 收藏0
  • [LeetCode/LintCode] Is Subsequence

    Problem Given a string s and a string t, check if s is subsequence of t. You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) ...

    terasum 评论0 收藏0
  • [LeetCode/LintCode] Odd Even Linked List

    Problem Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. Example Example:Given...

    awokezhou 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<