File tree Expand file tree Collapse file tree 2 files changed +72
-0
lines changed Expand file tree Collapse file tree 2 files changed +72
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments