Skip to content

Commit 848d491

Browse files
committed
fibnacci
1 parent e1c6489 commit 848d491

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package problem09;
2+
3+
/**斐波那契数列
4+
* Created by bjyangrubing on 2016/8/16.
5+
*/
6+
public class Fibonacci
7+
{
8+
/**
9+
* 递归的方式
10+
*/
11+
public int fib(int n)
12+
{
13+
if (n <= 0)
14+
{
15+
return 0;
16+
}
17+
if (n == 1)
18+
{
19+
return 1;
20+
}
21+
return fib(n - 1) + fib(n - 2);
22+
}
23+
24+
/**
25+
* 非递归,递推的方式
26+
*/
27+
public int fib2(int n)
28+
{
29+
int[] result =
30+
{ 0, 1 };
31+
if (n < 2)
32+
return result[n];
33+
int fibNMinusOne = 1;
34+
int fibNMinusTwo = 0;
35+
int fibN = 0;
36+
for (int i = 2; i <= n; i++)
37+
{
38+
fibN = fibNMinusOne + fibNMinusTwo;
39+
fibNMinusTwo = fibNMinusOne;
40+
fibNMinusOne = fibN;
41+
}
42+
43+
return fibN;
44+
45+
}
46+
47+
public static void main(String args[])
48+
{
49+
System.out.println(new Fibonacci().fib2(5));
50+
}
51+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package problem09;
2+
3+
import junit.framework.Assert;
4+
import org.junit.Test;
5+
6+
/**
7+
* Created by bjyangrubing on 2016/8/16.
8+
*/
9+
public class FibonacciTest
10+
{
11+
@Test
12+
public void test()
13+
{
14+
Fibonacci fibonacci = new Fibonacci();
15+
Assert.assertEquals(5, fibonacci.fib(5));
16+
}
17+
}

0 commit comments

Comments
 (0)