Skip to content

Commit 5b11fab

Browse files
committed
#509: Fibonacci Number; solution & tests
1 parent 8caf3c8 commit 5b11fab

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* 509
3+
* Fibonacci Number
4+
**
5+
* The Fibonacci numbers,
6+
* commonly denoted F(n) form a sequence,
7+
* called the Fibonacci sequence,
8+
* such that each number is the sum of the two preceding ones,
9+
* starting from 0 and 1.
10+
*
11+
* That is,
12+
* F(0) = 0, F(1) = 1
13+
* F(n) = F(n - 1) + F(n - 2), for n > 1.
14+
*
15+
* Given n, calculate F(n).
16+
*
17+
* Example 1:
18+
* Input: n = 2
19+
* Output: 1
20+
* Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
21+
*
22+
* Example 2:
23+
* Input: n = 3
24+
* Output: 2
25+
* Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
26+
*
27+
* Example 3:
28+
* Input: n = 4
29+
* Output: 3
30+
* Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
31+
*
32+
* Constraints:
33+
* • 0 <= n <= 30
34+
**
35+
* https://leetcode.com/problems/fibonacci-number/
36+
***/
37+
38+
namespace Problems;
39+
40+
public class FibonacciNumber
41+
{
42+
public int Fib( int n )
43+
{
44+
if ( n == 0 )
45+
{
46+
return 0;
47+
}
48+
49+
int prev = 0;
50+
int result = 1;
51+
52+
while ( n-- > 1 )
53+
{
54+
(prev, result) = (result, result + prev);
55+
}
56+
57+
return result;
58+
}
59+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
using NUnit.Framework;
2+
3+
using Problems;
4+
5+
public class FibonacciNumberTests
6+
{
7+
[TestCase( 2, ExpectedResult = 1 )]
8+
[TestCase( 3, ExpectedResult = 2 )]
9+
[TestCase( 4, ExpectedResult = 3 )]
10+
[TestCase( 0, ExpectedResult = 0 )]
11+
public int FibTest( int n ) =>
12+
new FibonacciNumber().Fib( n );
13+
}

0 commit comments

Comments
 (0)