Shirlies
宁静专注认真的程序媛~

题目

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。

n<=39

链接

http://www.nowcoder.com/practice/c6c7742f5ba7442aada113136ddea0c3?tpId=13&tqId=11160&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

代码

 1 class Solution {
 2 public:
 3     int Fibonacci(int n) {
 4         if(n == 0){
 5             return 0;
 6         }
 7         if(n == 1 || n == 2){
 8             return 1;
 9         }
10         
11         int first = 1;
12         int second = 1;
13         int next;
14         for(int index = 3; index <= n; ++ index){
15             next = first + second;
16             first = second;
17             second = next;
18         }
19         
20         return next;
21     }
22 };
View Code

 

posted on 2016-08-16 16:26  Shirlies  阅读(230)  评论(0)    收藏  举报