大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。n<=39
斐波那契数列定义为第一个数和第二个数相加等于第三个数
例如0、1、1、2、3、5、8、13、21、34
public class Solution {
public int Fibonacci(int n) {
int Prepre = 0;//第0项,相对于当前项的前面的前面项
int pre = 1;//第一项,相对于当前项的前面项
int result=0;//初始化
if(n == 0){//0时为0,没有规律,因为就1项
return 0;
}
if(n == 1){//1时为1,没有规律,因为目前就0,1
return 1;
}
for(int i = 2; i<= n;i++){//从第三个位置时,将prepre和pre相加
result = Prepre + pre;//新和
Prepre = pre;//将pre切换成prepre,也就是prepre指针后移
pre = result;//新的pre为上次的和,pre指针后移到和的位置
}
return result;
}
}```