Skip to content

Commit 7eae857

Browse files
committed
Fibonacci number.
1 parent 11935cf commit 7eae857

File tree

4 files changed

+57
-0
lines changed

4 files changed

+57
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
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+
Input: n = 2
12+
Output: 1
13+
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
14+
15+
Example 2:
16+
Input: n = 3
17+
Output: 2
18+
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
19+
20+
Example 3:
21+
Input: n = 4
22+
Output: 3
23+
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
24+
 
25+
26+
Constraints:
27+
- 0 <= n <= 30
28+
*/
29+
class Solution {
30+
func fib(_ n: Int) -> Int {
31+
if n == 1 { return 1 }
32+
if n == 0 { return 0 }
33+
var sum = [0, 1]
34+
var current = 0
35+
for i in 2...n {
36+
current = sum[i - 1] + sum[i - 2]
37+
sum.append(current)
38+
}
39+
return sum.last!
40+
}
41+
}
42+
43+
let s = Solution()
44+
let r = s.fib(4)
45+
print(r)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

Easy/509.Fibonacci Number.playground/playground.xcworkspace/contents.xcworkspacedata

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@
104104
100. [Base 7](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/504.Base%207.playground/Contents.swift)
105105
101. [Relative Ranks](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/506.Relative%20Ranks.playground/Contents.swift)
106106
102. [Perfect Number](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/507.Perfect%20Number.playground/Contents.swift)
107+
103. [Fibonacci Number](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/509.Fibonacci%20Number.playground/Contents.swift)
107108

108109
#### Medium
109110

0 commit comments

Comments
 (0)