我已经通过这道算法题!大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)。 n≤39n\leq 39n≤39
https://gw-c.nowcoder.com/api/sparta/jump/link?link=https%3A%2F%2Fwww.nowcoder.com%2FquestionTerminal%2Fc6c7742f5ba7442aada113136ddea0c3
全部评论
public class Solution {
public int Fibonacci(int n) {
if(n==0){
return 0;
}else if (n==1){
return 1;
}else {
return Fibonacci(n-1)+Fibonacci(n-2);
}
}
}
public class Solution {
public int Fibonacci(int n) {
if (n == 0 || n == 1) return n;
int a = 0;
int b = 1;
int c = 0;
for (int i=2; i<=n; ++i) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
相关推荐
![](https://static.nowcoder.com/fe/file/oss/1715049343797JOCFB.png)
点赞 评论 收藏
分享