[Leetcode] Factorial Trailing Zeroes

Source: Internet
Author: User

Title: (Math)

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

Note:your solution should is in logarithmic time complexity.

Exercises


Let's start by listing a few examples to find out the rules.

and found

5! There's a 0,

10! There are two of 0,

15! There are three of 0,

20! There are four of 0,

25! There are six of 0,.

It can be seen that when n is greater than or equal to 5 it can produce a suffix of 0, because 5*2=10. and 2 is certainly not missing because as long as there is an even number 2.

So we just need to count n!. Contains 5 of the number can be.

At first, I thought it would be as long as N/5. Later found, for example, 25, contains two 5,25=5*5. So it is found that the total number of 5 equals the number after N/5 divided by 5 until it is less than 5.

 Public classSolution { Public intTrailingzeroes (intN) {if(n<4)          return 0; intres=0;  while(n>=5) {res+=n/5; N=n/5; }        returnRes; }}

[Leetcode] Factorial Trailing Zeroes

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.