Fibonacci

题目:

Find the Nth number in Fibonacci sequence. A Fibonacci sequence is defined as follow:

The first two numbers are 0 and 1. The i th number is the sum of i-1 th number and i-2 th number. The first ten numbers in Fibonacci sequence is:

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

分析:

题目逻辑特别直接,别写bug就好了。

解法:

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

results matching ""

    No results matching ""