题目:
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
分析:
斐波那契数列是0,1,1,2,3,5,8,13...也就是当前的数字是前两个数字之和。
题目很简单求出斐波那契数列第n项。
程序:
C++
class Solution { public: int Fibonacci(int n) { if(n == 0) return 0; if(n == 1) return 1; int fNum = 0; int sNum = 1; int temp = 0; for(int i = 2; i <= n; ++i){ temp = sNum; sNum = fNum + sNum; fNum = temp; } return sNum; } };
Java
public class Solution { public int Fibonacci(int n) { if(n == 0) return 0; if(n == 1) return 1; int fNum = 0; int sNum = 1; int temp = 0; for(int i = 2; i <= n; ++i){ temp = sNum; sNum = fNum + sNum; fNum = temp; } return sNum; } }