Skip to content

Commit d07fd5a

Browse files
authored
Create 04 - Space Optimized | DP | Approach.cpp
1 parent f2af4e7 commit d07fd5a

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public:
3+
int nthFibonacci(int n) {
4+
// Base case: If n is 0, return 0 (F(0) = 0)
5+
if (n == 0)
6+
return 0;
7+
8+
// Base case: If n is 1, return 1 (F(1) = 1)
9+
if (n == 1)
10+
return 1;
11+
12+
// Initialize the first two Fibonacci numbers
13+
int a = 0; // F(0)
14+
int b = 1; // F(1)
15+
16+
// Variable to store the current Fibonacci number
17+
int m = 0;
18+
19+
// Loop from 2 to n to calculate the nth Fibonacci number iteratively
20+
for (int i = 2; i <= n; i++) {
21+
// The nth Fibonacci number is the sum of the previous two numbers
22+
m = a + b;
23+
24+
// Update a and b for the next iteration
25+
a = b; // Move to the next value in the sequence
26+
b = m; // Current Fibonacci number becomes the next "b"
27+
}
28+
29+
// Return the nth Fibonacci number
30+
return m;
31+
}
32+
};

0 commit comments

Comments
 (0)