題目描述:給定一個(gè)整數(shù)n,返回n!(n的階乘)數(shù)字中的后綴0的個(gè)數(shù)。
方法一:sum可能會(huì)溢出
int trailingZeroes(int n) {
int sum = 1;
for (int i = 1; i <= n; i++) {
sum *= i;
}
int count = 0;
while ((sum % 10) == 0) {
sum /= 10;
count++;
}
return count;
}
方法二:解決了第一版中的溢出問題
int trailingZeroes(int n) {
int count2 = 0;
int count5 = 0;
for (int i = 1; i <= n; i++) {
int j = i;
while (j != 0 && j % 2 == 0) {
j /= 2;
count2++;
}
j = i;
while (j != 0 && j % 5 == 0) {
j /= 5;
count5++;
}
}
return count2 < count5 ? count2 : count5;
}
方法三:這個(gè)版本我是百度的,請(qǐng)點(diǎn)這兒,好好看一下數(shù)學(xué)原理解釋
int trailingZeroes(int n) {
int count = 0;
while (n != 0) {
count += n / 5;
n /= 5;
}
return count;
}