美文网首页
Day7 剑指offer:斐波那契数列

Day7 剑指offer:斐波那契数列

作者: zheng7 | 来源:发表于2017-08-06 21:24 被阅读0次

大家都知道斐波那契数列(1 1 2 3 5 8 13),现在要求输入一个整数n,请你输出斐波那契数列的第n项。
n<=39

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

相关文章

网友评论

      本文标题:Day7 剑指offer:斐波那契数列

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