Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Dec 19, 2023. It is now read-only.

Commit b618034

Browse files
committed
Add problem 509
1 parent 757ae04 commit b618034

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

‎algorithms/509/README.md‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
## 509. Fibonacci Number
2+
3+
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,
4+
5+
<pre>
6+
F(0) = 0, F(1) = 1
7+
F(N) = F(N - 1) + F(N - 2), for N > 1.
8+
</pre>
9+
10+
Given `N`, calculate `F(N)`.
11+
12+
<br>
13+
14+
**Example 1:**
15+
<pre>
16+
<b>Input:</b> 2
17+
<b>Output:</b> 1
18+
<b>Explanation:</b> F(2) = F(1) + F(0) = 1 + 0 = 1.
19+
</pre>
20+
21+
**Example 2:**
22+
<pre>
23+
<b>Input:</b> 3
24+
<b>Output:</b> 2
25+
<b>Explanation:</b> F(3) = F(2) + F(1) = 1 + 1 = 2.
26+
</pre>
27+
28+
**Example 3:**
29+
<pre>
30+
<b>Input:</b> 4
31+
<b>Output:</b> 3
32+
<b>Explanation:</b> F(4) = F(3) + F(2) = 2 + 1 = 3.
33+
</pre>
34+
35+
<br>
36+
37+
**Note:**
38+
39+
0 ≤ `N` ≤ 30.

‎algorithms/509/solution.go‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package main
2+
3+
// Time complexity, O(N)
4+
// Space complexity, O(1)
5+
func fib(N int) int {
6+
if N == 0 {
7+
return 0
8+
} else if N < 3 {
9+
return 1
10+
}
11+
var res int
12+
for f, s, i := 1, 1, 3; i <= N; i++ {
13+
res = f + s
14+
f, s = s, res
15+
}
16+
return res
17+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /