题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。
n<=39
思路
/*
* 思路一:递归就不用考虑了,肯定会溢出,占用空间太大了,可以用循环
*/
class Solution {
public:
int Fibonacci(int n) {
if(n <= 0) {
return 0;
}
if(n == 1) {
return 1;
}
if(n == 2) {
return 1;
}
int f1 = 1, f2 = 1;
int tem;
for(int i = 3; i <= n; i++){
tem = f2;
f2 = f1+f2;
f1 = tem;
}
//int f1 = 0, f2 = 1;
//n--;
//while(n--) {
// f2 += f1;
// f1 = f2 - f1;
//}
return f2;
}
};
JS实现
function Fibonacci(n)
{
if(n <= 0) return 0;
if(n == 1) return 1;
if(n == 2) return 1;
var f1 = 0,f2 = 1;
n--;
while(n--){
f2 += f1;
f1 = f2-f1;
}
return f2;
}