【LeetCode】Factorial Trailing Zeroes 解题报告
2016-05-08 18:51
441 查看
【LeetCode】Factorial Trailing Zeroes 解题报告
[LeetCode]https://leetcode.com/problems/factorial-trailing-zeroes/
Total Accepted: 58324 Total Submissions: 177641 Difficulty: Easy
Question
Given an integer n, return the number of trailing zeroes in n!.Note: Your solution should be in logarithmic time complexity.
Ways
这个题一看就不能暴力求解。分析一下,就是看n!有多少个5组成。
计算包含的2和5组成的pair的个数就可以了。
因为5的个数比2少,所以2和5组成的pair的个数由5的个数决定。
观察15! = 有3个5(来自其中的5, 10, 15), 所以计算n/5就可以。
但是25! = 有6个5(有5个5来自其中的5, 10, 15, 20, 25, 另外还有1个5来自25=(5*5)的另外一个5),
所以除了计算n/5, 还要计算n/5/5, n/5/5/5, n/5/5/5/5, …, n/5/5/5,,,/5直到商为0。
算法中这个count += n / i;的意思是直接看有多少个5.
比如n=26;那么,26/5=5;26/25=1;所以结果是5+1=6个。
方法比较巧妙,反正我是没想出来。
另外注意,一定用long,int的话结果不对,我是一脸懵逼不知道为啥。
public class Solution { public int trailingZeroes(int n) { if(n<=0) return 0; int count = 0; for (long i = 5; n / i >= 1; i *= 5) { count += n / i; } return count; } }
AC:1ms
Date
2016 年 05月 8日相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解