Einfach 0 gelöst 0% Erfolgsquote

Factorial

Multiply all positive integers up to n.

Das lernst du

  • Multiply a sequence of numbers with a loop
  • Start a product at 1 instead of 0
  • See how quickly factorials grow

Problem

Übersetzung anzeigen

The factorial of n, written n!, is 1 × 2 × … × n. By definition 0! = 1.

Implement factorial(n).

Input

n: A non-negative integer.

Output

Return n!.

Einschränkungen

0 ≤ n ≤ 20, so the result fits a signed 64-bit integer.

Beispiele

Beispiel 1
Eingabe:
n = 5

Erwartete Ausgabe:
expected = 120
Eingabe:
long long n = 5;

Erwartete Ausgabe:
long long expected = 120;
Eingabe:
long n = 5;

Erwartete Ausgabe:
long expected = 120;

Erläuterung

1 × 2 × 3 × 4 × 5 = 120.

Beispiel 2
Eingabe:
n = 0

Erwartete Ausgabe:
expected = 1
Eingabe:
long long n = 0;

Erwartete Ausgabe:
long long expected = 1;
Eingabe:
long n = 0;

Erwartete Ausgabe:
long expected = 1;

Erläuterung

0! is defined as 1.

So gehst du vor

Versuch es zuerst allein und öffne dann einen Hinweis nach dem anderen.

Hinweis 1

Factorial multiplies all integers from 1 up to the given number.

Hinweis 2

An iterative running product is enough, and 0 has a special defined result.

Hinweis 3

Because the input is small, overflow is the main detail to watch for in other languages.

Erwartete Komplexität

O(n) time, O(1) extra space

Die beste bestandene Lösung jedes Coders. Schnellere, sparsamere und besser bewertete Lösungen stehen weiter oben.

Noch keine bestandene Lösung. Löse sie und hol dir Platz eins.

Von anderen lernen

Community-Lösungen

Noch keine veröffentlichten Lösungen. Löse die Aufgabe und teile als Erster eine Lösung.