LeetCode 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.

 


题目标签:Math

  题目要求我们找到末尾0的数量。

  只有当有10的存在,才会有0,比如 2 * 5 = 10; 4 * 5 = 20; 5 * 6 = 30; 5 * 8 = 40 等等,可以发现0 和 5 的联系。

  所以这一题也是在问 n 里有多少个5。

  需要注意的一点是,25 = 5 * 5; 125 = 5 * 5 * 5 等等

 

 

 

Java Solution:

Runtime beats 42.46% 

完成日期:01/16/2018

关键词:Math

关键点:0 和 5 的联系

 1 class Solution 
 2 {
 3     public int trailingZeroes(int n) 
 4     {
 5         int zeros = 0;
 6         
 7         while(n > 0)
 8         {
 9             zeros += n / 5;
10             n = n / 5;
11         }
12         
13         return zeros;
14     }
15 }

参考资料:N/A

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2018-01-17 13:00  Jimmy_Cheng  阅读(171)  评论(0编辑  收藏  举报