题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39。
解决方法
public class Solution {
public int Fibonacci(int n) {
// 索引位置 : 1 2 3 4 5 6 7
// 数列形式 : 0 1 1 2 3 5 8 13
if(n == 1){
return 1;
}
if(n == 2){
return 1;
}
// 由于 n <= 39 ,因而可以采用递归方法,实际上还是栈溢出,因而用迭代吧
int first = 1;
int second = 1;
int result = 0;
for(int i = 3; i <= n; i ++){
result = first + second;
first = second;
second = result;
}
return result;
}
}