The Fibonacci Number solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Fibonacci Number
C++, Python and TypeScript solutions for Fibonacci Number.
Solution files
Python•fibonacci-number/synced-solution.py
class Solution:
def fib(self, n: int) -> int:
if n < 2:
return n
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b
C++•fibonacci-number/synced-solution.cpp
class Solution {
public:
int fib(int n) {
if (n < 2) {
return n;
}
int a = 0;
int b = 1;
for (int i = 2; i <= n; i++) {
int next = a + b;
a = b;
b = next;
}
return b;
}
};
TypeScript•fibonacci-number/synced-solution.ts
function fib(n: number): number {
if (n < 2) {
return n;
}
let a = 0;
let b = 1;
for (let i = 2; i <= n; i++) {
const next = a + b;
a = b;
b = next;
}
return b;
}