[172] Factorial Trailing Zeroes
2016-07-22 10:48
357 查看
1. 题目描述
Given an integer n, return the number of trailing zeroes in n!.Note: Your solution should be in logarithmic time complexity.
给定一个整数n,求n!中有多少个0。
2. 解题思路
n! = 1*2*….*n-1*n,题目要求求一个数的阶乘中有多少0,但是真的需要老老实实的把从1乘到n之后再数才能得出n的阶乘中0的个数嘛?显然不是的。要得到一个0,那么可能的值就是2^n*(5*m),当m=1-4时,可以得到1个0,如15*4=60,m=5时可以得到两个0,如25*8=100,依次类推,m=5^k时,可以得到k个0。3. Code
public class Solution { public int trailingZeroes(int n) { // 2*5 10 4*15 20 8*25 30 ... 100 int result = 0; while(n >= 5) { // 30的阶乘有7个0,5,10,15,20,25(2),30 result += (int)(n/5); n/=5; } return result; } }
相关文章推荐
- shell 中数学计算总结
- PHP几个数学计算的内部函数学习整理
- 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 题解