版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85273827
Title:Factorial Trailing Zeroes 172
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/factorial-trailing-zeroes/
1. 求5的因数
时间复杂度:O(nlogn),for循环嵌套while循环。
空间复杂度:O(1),没有申请额外空间。
/**
* 求每个数含有5因数的个数
* @param n
* @return
*/
public static int trailingZeroes(int n) {
if (n <= 4) {
return 0;
}
int count = 0;
for (int i = 5; i <= n; i+=5) {
int num = i;
while (num > 0) {
if (num % 5 == 0) {
count++;
num /= 5;
}
else {
break;
}
}
}
return count;
}
2. 求5的因数
时间复杂度:O(logn),while循环。
空间复杂度:O(1),没有申请额外空间。
/**
* 求5的因数,while循环
* @param n
* @return
*/
public static int trailingZeroes1(int n) {
int res = 0;
while (n > 0) {
res += n / 5;
n /= 5;
}
return res;
}
2. 求5的因数
时间复杂度:O(logn),递归。
空间复杂度:O(1),没有申请额外空间。
/**
* 求5的因数,递归
* @param n
* @return
*/
public static int trailingZeroes2(int n) {
if (n < 5) {
return 0;
}
if (n < 10) {
return 1;
}
return n / 5 + trailingZeroes2(n / 5);
}