首页 > 其他 > 详细

lintcode-easy-Fibonacci

时间:2016-02-18 13:52:35      阅读:214      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

lintcode-easy-Fibonacci

原文:http://www.cnblogs.com/goblinengineer/p/5197836.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!