美文网首页
斐波那契数列

斐波那契数列

作者: 雨的印记2012 | 来源:发表于2019-06-16 22:09 被阅读0次

牛客网(java实现)


问题描述:

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。n<=39

问题分析:

用for循环实现非递归

算法实现:

参考代码:

public class Solution {
    public int Fibonacci(int n) {
        if (n == 0)
            return 0;
        else if (n == 1)
            return 1;
        int a = 0,b = 1;
        int tmp = 0;
        for (int i=2; i<=n; i++)
        {
            tmp = b;
            b = a+b;
            a = tmp;
        }
        return b;
    }
}

相关文章

网友评论

      本文标题:斐波那契数列

      本文链接:https://www.haomeiwen.com/subject/ocenfctx.html