1. 程式人生 > >劍指offer____斐波那契數列

劍指offer____斐波那契數列

大家都知道斐波那契數列,現在要求輸入一個整數n,請你輸出斐波那契數列的第n項(從0開始,第0項為0)。

class Solution {
public:
    int Fibonacci(int n) {
       /* if(n <= 0) return 0;
        if(n <= 1) return 1;
        return Fibonacci(n-1)+Fibonacci(n-2);
        */
        if(n <= 0) return 0;
        if(n <= 1) return 1;
        int fib_one = 1;
        int fib_two = 0;
        int fib_num = 1;
        for(int i = 2; i <= n; ++i)
        {
            fib_num=fib_one+fib_two;
            fib_two=fib_one;
            fib_one=fib_num;
        }
        return fib_num;
    }
};