โจทย์
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!.
เงื่อนไข
0 ≤ n ≤ 20, so the result fits a signed 64-bit integer.
ตัวอย่าง
อินพุต:
n = 5
ผลลัพธ์ที่คาดหวัง:
expected = 120
อินพุต:
long long n = 5;
ผลลัพธ์ที่คาดหวัง:
long long expected = 120;
อินพุต:
long n = 5;
ผลลัพธ์ที่คาดหวัง:
long expected = 120;
คำอธิบาย
1 × 2 × 3 × 4 × 5 = 120.
อินพุต:
n = 0
ผลลัพธ์ที่คาดหวัง:
expected = 1
อินพุต:
long long n = 0;
ผลลัพธ์ที่คาดหวัง:
long long expected = 1;
อินพุต:
long n = 0;
ผลลัพธ์ที่คาดหวัง:
long expected = 1;
คำอธิบาย
0! is defined as 1.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
Factorial multiplies all integers from 1 up to the given number.
คำใบ้ 2
An iterative running product is enough, and 0 has a special defined result.
คำใบ้ 3
Because the input is small, overflow is the main detail to watch for in other languages.
ความซับซ้อนที่คาดหวัง
O(n) time, O(1) extra space