Fibonacci

题目描述[原题链接][https://www.acwing.com/problem/content/19/]

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

假定从0开始,第0项为0。(n<=39)

样例

1
2
3
输入整数 n=5 

返回 5

算法描述

简单斐波那契数列,爬楼梯问题

C++代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int Fibonacci(int n) {
if(n==0||n==1)return n;
int a = 0;
int b = 1;
int t = 0;
while(n-- > 1){
t = a+b;
a = b;
b = t;
}
return t;
}
};

Java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int Fibonacci(int n) {
if(n==0||n==1)return n;
int a=0,b=1,t=0;
n--;
while(n--!=0){
t=a+b;
a=b;
b=t;
}
return t;
}
}