[Leetcode] Factorial Trailing Zeros

Source: Internet
Author: User

Well, to compute the number of trailing zeros, we need to first think clear on what would generate a trailing 0 ? Obviously, a number multiplied by would has 10 a trailing 0 added to it. So we are need to find out how many's would appear in the expression of the 10 factorial. Since 10 = 2 * 5 and there is a bunch more 2 ' s (each even number would contribute at least one 2 ), we only need to count The number of 5 ' s.

Now let's see what numbers'll contribute a  5 . Well, simply the multiples of  5 , like  5, ten,, ... . So is the result simply  n/5 ? Well, not. Notice that some numbers could contribute more than one  5 , like  5 * 5 . Well, what numbers would contribute more than one  5 ? Ok, notice that is only multiples of the power of  5  will contribute more than one  5 . For example, multiples of   will contribute at least two  5 '.

Well, what to count them all? If You try some examples, you may finally get the result, which is n / 5 + n / 25 + n / 125 + ... . The idea behind this expression Is:all 5 the multiples of'll contribute one 5 , the multiples of'll 25 cont Ribute one more and the multiples of'll contribute another one more ... and so on 5 125 5 . Now, we can write down the following code, which are pretty short.

1 classSolution {2  Public:3     intTrailingzeroes (intN) {4         intCount =0;5          for(Long Longi =5; n/i; I *=5)6Count + = n/i;7         returncount;8     }9};

[Leetcode] Factorial Trailing Zeros

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.