172
選択した UI 言語に合わせて問題文をロシア語から翻訳します。コードは変更しません。
. Factorial Trailing Zeroes
given 整数 n, return количество конечных нулей в n!.
Обратите внимание, что n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.
例:
Input: n = 3
Output: 0
Explanation: 3! = 6, no trailing zero.
C# 解法
照合済み/オリジナルclass Solution {
public int TrailingZeroes(int n) {
BigInteger nFactorial = BigInteger.One;
for (int i = 2; i <= n; i++) {
nFactorial *= i;
}
int zeroCount = 0;
while (nFactorial % 10 == 0) {
nFactorial /= 10;
zeroCount++;
}
return zeroCount;
}
}
C++ 解法
自動ドラフト、提出前に確認#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public int TrailingZeroes(int n) {
BigInteger nFactorial = BigInteger.One;
for (int i = 2; i <= n; i++) {
nFactorial *= i;
}
int zeroCount = 0;
while (nFactorial % 10 == 0) {
nFactorial /= 10;
zeroCount++;
}
return zeroCount;
}
}
Java 解法
自動ドラフト、提出前に確認import java.util.*;
import java.math.*;
// Auto-generated Java draft from the C# solution. Review API differences before LeetCode submit.
class Solution {
public int TrailingZeroes(int n) {
BigInteger nFactorial = BigInteger.One;
for (int i = 2; i <= n; i++) {
nFactorial *= i;
}
int zeroCount = 0;
while (nFactorial % 10 == 0) {
nFactorial /= 10;
zeroCount++;
}
return zeroCount;
}
}
Algorithm
1️⃣
Вычислите факториал n:
Инициализируйте переменную nFactorial значением 1.
Для каждого i от 2 до n включительно умножайте nFactorial на i.
2️⃣
Подсчитайте количество конечных нулей в nFactorial:
Инициализируйте переменную zeroCount значением 0.
Пока nFactorial делится на 10 без остатка, делите его на 10 и увеличивайте zeroCount на 1.
3️⃣
return значение zeroCount как количество конечных нулей в n!.
😎
Vacancies for this task
有効な求人 with overlapping task tags are 表示.
有効な求人はまだありません。