您的位置:首页 > 其它

斐波那契数列

2016-06-20 23:56 204 查看

题目

要求输入一个整数n,请你输出斐波那契数列的第n项。

解题

方法一:递归

public class Solution {
public int Fibonacci(int n) {
if(n <=0)
return 0;
if(n==1)
return 1;
if(n==2)
return 1;
return Fibonacci(n-1) + Fibonacci(n-2);
}
}


溢出

方法二:循环

public class Solution {
public int Fibonacci(int n) {
int f0 = 0;
int f1 = 1;
int f2 = 1;
if(n <=0)
return f0;
if(n==1)
return f1;
while(n>=2){
f2 = f0 + f1;
f0 = f1;
f1 = f2;
n--;
}
return f1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: