[2ND TRY]
class Solution {
public int trailingZeroes(int n) {
// given a number, how can we calculate trailing zeros of its factorial
// e.g. 10 -> 1 2 3 4 5 6 7 8 9 10 -> 5(2) -> 2
// 25 -> 1..5..10..15..20..25 -> 5(5) + 25(1) -> although in 25 we have two 5s, one of them is already counted in count of 5s
// so every time we count how many 5,25,125... are their less than num, and add them together
int counter = 0;
while (n > 0) {
counter += n / 5;
n /= 5;
}
return counter;
}
}
[1ST TRY]
先找有多少个5
然后找有多少个25
然后找有多少个625
bug是temp一开始overflow了
89.52 %
class Solution {
public int trailingZeroes(int n) {
long temp = 5;
int result = 0;
while (temp <= n) {
result += n / temp;
temp *= 5;
}
return result;
}
}
No comments:
Post a Comment