题目:
Java代码如下:
package demo;
public class TestFibonacci {
public static long fibonacci(int n) {
if(n <= 0) {
return 0;
}
if(n == 1) {
return 1;
}
// 记录第n-2个Fibonacci数的值
long prePre = 0;
// 记录第n-1个Fibonacci数的值
long pre = 1;
// 记录第n个Fibonacci数的值
long current = 1;
/**
* 求解第n个Fibonacci数的值
*/
for(int i = 2; i <= n; i++) {
// 第i个Fibonacci数的值
current = prePre + pre;
// 更新结果:原先记录第i-2个数,现在记录第i-1个数
prePre = pre;
// 更新结果:原先记录第i-1个数,现在记录第i个数
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(5));
System.out.println(fibonacci(10));
System.out.println(fibonacci(40));
System.out.println(fibonacci(50));
System.out.println(fibonacci(100));
}
}