斐波納契數列

查找斐波納契數列中第 N 個數。

所謂的斐波納契數列是指:

前2個數是 0 和 1 。
第 i 個數是第 i-1 個數和第i-2 個數的和。
斐波納契數列的前10個數字是:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 …

樣例
給定 1,返回 0

給定 2,返回 1

給定 10,返回 34

思路:通過定義三個變量來進行

class Solution {
public:
    /*
     * @param : an integer
     * @return: an ineger f(n)
     */
    int fibonacci(int n) {
        // write your code here
        int a=0, b=1, c, i;
        if(n == 1) return 0;
        if(n == 2) return 1;
        for(i=0; i<n-2; i++)
        {
            c=a+b;
            a=b;
            b=c;

        }
        return c;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章