-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathWarmup_.cpp
More file actions
31 lines (27 loc) · 960 Bytes
/
Warmup_.cpp
File metadata and controls
31 lines (27 loc) · 960 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
UCLA ACM ICPC: Interview Track Problem Solutions
Disclaimer: This is not the only valid solution and we do not claim our solutions
to be optimal in terms of runtime or memory usage, we are merely giving example
solutions to questions for learning purposes only
Factorial
*/
// Given a non-negative integer n, return n!
// Note: n! = n * (n - 1) * (n - 2) * ... * 2 * 1;
// A special case if that 0! = 1
class Solution {
public:
// We will use simple recursion to solve this problem.
int factorial(int n) {
// If n == 0 or n == 1, trivially, we return 1
if(n == 0 || n == 1) {
return 1;
}
// The factorial has a recursive definition.
// Note that (n - 1)! = (n - 1) * (n - 2) * ... * 2 * 1.
// We can then say that n! = n * (n - 1) * (n - 2) * ... * 2 * 1
// = n * (n - 1)!
else {
return n * factorial(n - 1);
}
}
};