美文网首页剑指offer
剑指offer(七)斐波那契数列

剑指offer(七)斐波那契数列

作者: 向前的zz | 来源:发表于2020-04-07 10:07 被阅读0次

点击进入 牛客网题库:斐波那契数列

题目描述

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

方法一 递归法

 public int Fibonacci(int n) {
        if(n == 0) {
            return 0;
        }
        if(n == 1) {
            return 1;
        }
        if(n == 2) {
            return 1;
        }
        
        return Fibonacci(n-1) + Fibonacci(n-2);
        
    }

方法二 迭代法

public int Fibonacci(int n) {
        if(n == 0) {
            return 0;
        }
        if(n == 1) {
            return 1;
        }
        if(n == 2) {
            return 1;
        }
        
        int i = 1;
        int j = 1;
        while(--n > 1) {
            int tmp = i;
            i = j;
            j = tmp + j;
            
        }
        return j;
}

相关文章

网友评论

    本文标题:剑指offer(七)斐波那契数列

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