forked from Wang-Jun-Chao/coding-interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTest09.java
More file actions
59 lines (52 loc) · 1.57 KB
/
Test09.java
File metadata and controls
59 lines (52 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* Author: 王俊超
* Date: 2015-04-23
* Time: 09:09
* Declaration: All Rights Reserved !!!
*/
public class Test09 {
/**
* 写一个函数,输入n,求斐波那契(Fibonacci) 数列的第n项
* @param n Fibonacci数的项数
* @return 第n项的结果
*/
public static long fibonacci(int n) {
// 当输入非正整数的时候返回0
if (n <= 0) {
return 0;
}
// 输入1或者2的时候返回1
if (n == 1 || n == 2) {
return 1;
}
// 记录前两个(第n-2个)的Fibonacci数的值
long prePre = 1;
// 记录前两个(第n-1个)的Fibonacci数的值
long pre = 1;
// 记录前两个(第n个)的Fibonacci数的值
long current = 2;
// 求解第n个的Fibonacci数的值
for (int i = 3; i <= n ; i++) {
// 求第i个的Fibonacci数的值
current = prePre + pre;
// 更新记录的结果,prePre原先记录第i-2个Fibonacci数的值
// 现在记录第i-1个Fibonacci数的值
prePre = pre;
// 更新记录的结果,pre原先记录第i-1个Fibonacci数的值
// 现在记录第i个Fibonacci数的值
pre = current;
}
// 返回所求的结果
return current;
}
public static void main(String[] args) {
System.out.println(fibonacci(0));
System.out.println(fibonacci(1));
System.out.println(fibonacci(2));
System.out.println(fibonacci(3));
System.out.println(fibonacci(4));
System.out.println(fibonacci(5));
System.out.println(fibonacci(6));
System.out.println(fibonacci(7));
}
}