fibonacci数列的题目——剑指Offer

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

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

n<=39

class Solution {
public:
    int Fibonacci(int n) {
        if (n < 1) return 0;
        if (n <= 2) return 1;
        int fib2 = 1;
        int fib1 = 1;
        for (int i=3; i<=n; i++) {
            int tmp = fib2 + fib1;
            fib2 = fib1;
            fib1 = tmp;
        }
        return fib1;
    }
};

 

posted @ 2018-02-08 10:34  blcblc  阅读(139)  评论(0编辑  收藏  举报