Đề bài
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!.
Ràng buộc
0 ≤ n ≤ 20, so the result fits a signed 64-bit integer.
Ví dụ
Đầu vào:
n = 5
Kết quả mong đợi:
expected = 120
Đầu vào:
long long n = 5;
Kết quả mong đợi:
long long expected = 120;
Đầu vào:
long n = 5;
Kết quả mong đợi:
long expected = 120;
Giải thích
1 × 2 × 3 × 4 × 5 = 120.
Đầu vào:
n = 0
Kết quả mong đợi:
expected = 1
Đầu vào:
long long n = 0;
Kết quả mong đợi:
long long expected = 1;
Đầu vào:
long n = 0;
Kết quả mong đợi:
long expected = 1;
Giải thích
0! is defined as 1.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Factorial multiplies all integers from 1 up to the given number.
Gợi ý 2
An iterative running product is enough, and 0 has a special defined result.
Gợi ý 3
Because the input is small, overflow is the main detail to watch for in other languages.
Độ phức tạp mong đợi
O(n) time, O(1) extra space