版权声明:博客内容为本人自己所写,请勿转载。 https://blog.csdn.net/weixin_42805929/article/details/82970538
斐波那契数列 java
题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。其中:n<=39
代码1:
public class Solution {
public int Fibonacci(int n) {
int a = 0, b = 1;
int c = 0;
for(int i = 0; i <= n; i++){
if(i == 0){
c = a;
}else if(i == 1){
c = b;
}else if(i > 1){
c = a + b;
a = b;
b = c;
}
}
return c;
}
}
代码2:推荐
public class Solution {
public int Fibonacci(int n) {
int a = 0, b = 1;
int c = 0;
for(int i = 0; i <= n; i++){
if(i == 1){
c = b;
}else if(i > 1){
c = a + b;
a = b;
b = c;
}
}
return c;
}
}
代码3:采用递归方式
public class Solution {
public int Fibonacci(int n) {
int c = 0;
if(n == 0){
c = 0;
}else if(n == 1){
c = 1;
}else{
c = Fibonacci(n - 1) + Fibonacci(n - 2);
}
return c;
}
}