
class Solution {
public:
int Fibonacci(int n) {
if(n==0)return 0;
if(n==1)return 1;
int a=0,b=1,temp=0;
while(n>1){
temp=a+b;
a=b;
b=temp;
n--;
}
return b;
}
};
或者:
class Solution {
public:
int Fibonacci(int n) {
int f = 0, g = 1;
while(n--) {
g += f;
f = g - f;
}
return f;
}
};
本文提供了两种使用C++实现的斐波那契数列计算方法。第一种方法使用了两个变量a和b来交替存储斐波那契数列中的相邻两项,并通过一个临时变量temp进行中间值的传递。第二种方法则更为简洁,通过两个变量f和g在循环中不断更新值来计算斐波那契数。这两种方法都避免了递归带来的效率问题。
3603

被折叠的 条评论
为什么被折叠?



