lintcode-easy-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 ...

 

Note

The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.

 

 

网站上其实说这是naive级的题,没啥太多可说的,也许为一点改进就是常数空间复杂度吧,但是也比较清晰。

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

 

posted @ 2016-02-18 12:52  哥布林工程师  阅读(127)  评论(0编辑  收藏  举报