Codewars Java练习:Number of trailing zeros of N!

题目

Write a program that will calculate the number of trailing zeros in a factorial of a given number.

N! = 1 * 2 * 3 * ... * N

Be careful 1000! has 2568 digits…

For more info, see: http://mathworld.wolfram.com/Factorial.html

Examples

zeros(6) = 1
# 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero

zeros(12) = 2
# 12! = 479001600 --> 2 trailing zeros

Hint: You’re not meant to calculate the factorial. Find another way to find the number of zeros.

题解

这也是5级题???升级好慢==

统计1-n中5出现了多少次就好了。

public class Solution {
  public static int zeros(int n) {
      int result = 0;
      while (n!=0) {
        result += n/5;
        n /= 5;
      }
      return result;
  }
}

 

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据