本文主要是介绍LeetCode(31)-Factorial Trailing Zeroes,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
Given an integer n, return the number of trailing zeroes in n!.Note: Your solution should be in logarithmic time complexity.
思路:
- 题意是要求一个数字的阶乘,末尾有多少个0
- 要求是对数级别的时间,所以考虑用递归
- 分析一下,产生一个10,后面加0,找到所有的2*5,或者2的次方×5的次方,任何情况下因子2的个数永远大于5
- 所以只需要计算因子5的个数,(25*4 = 100),算2个5
- -
代码:
class Solution {/** param n: As desciption* return: An integer, denote the number of trailing zeros in n!*/public long trailingZeros(long n) {// write your code herereturn n / 5 == 0 ? 0 : n /5 + trailingZeros(n / 5);}
};
暴力方法:(不推荐)
public class Solution {public int trailingZeroes(int n) {int count = 0;if(get(n) == 0){return 1;}int sum = get(n);while(sum > 0){if(sum % 10 == 0){count++;}sum = sum /10;}return sum;}public int get(int n){int all = 0;if(n == 0){return 0;}for(int i = 1;i <= n;i++){all = all*i;}return all;}
}
这篇关于LeetCode(31)-Factorial Trailing Zeroes的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!