Skip to content

Commit 63c97c0

Browse files
authored
Create Fibonacci_Number.py
1 parent b935ffb commit 63c97c0

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Fibonacci_Number.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# 509. Fibonacci Number
2+
# The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
3+
4+
# F(0) = 0, F(1) = 1
5+
# F(n) = F(n - 1) + F(n - 2), for n > 1.
6+
# Given n, calculate F(n).
7+
8+
9+
10+
# Example 1:
11+
12+
# Input: n = 2
13+
# Output: 1
14+
# Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
15+
# Example 2:
16+
17+
# Input: n = 3
18+
# Output: 2
19+
# Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
20+
# Example 3:
21+
22+
# Input: n = 4
23+
# Output: 3
24+
# Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
25+
26+
27+
# Constraints:
28+
29+
# 0 <= n <= 30
30+
31+
# solution
32+
class Solution:
33+
def fib(self, n: int) -> int:
34+
if n == 0:
35+
print(0)
36+
elif n == 1:
37+
print(1)
38+
c = 0
39+
a = 0
40+
b = 1
41+
for i in range(1,n):
42+
c = a + b
43+
a = b
44+
b = c
45+
return c
46+

0 commit comments

Comments
 (0)