求斐波那契数列的第n项
public class Offer13 {
/**
* 递归方式:n过大,会发生栈溢出
*/
public static int fibonacci1(int n){
if(n==0)return 0;
if(n==1)return 1;
return fibonacci1(n-1)+fibonacci1(n-2);
}
/**
* 循环方式
*/
public static int fibonacci(int n){
if(n<0)return -1;
int[] result = {0,1};
if(n<2)return result[n];
int tempA = 0;
int tempB = 1;
int fibN = 0;
for (int i=2;i<=n;i++){
fibN = tempA+tempB;
tempA = tempB;
tempB = fibN;
}
return fibN;
}
}