斐波那契数列

来源:互联网 发布:复制淘口令淘宝没反应 编辑:程序博客网 时间:2024/06/05 05:37

题目描述:
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39
解题思路:
百度百科:斐波那契数列
斐波那契数列:0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …
利用for循环,对数组前两个数组不断叠加
解题思路:

    public int Fibonacci(int n) {        //n值的特殊情况        if (n>39 || n<0) return -1;        if (n==0) return 0;        if (n==1) return 1;        //从n=2开始叠加        int first=0, last=1;        int temp = 0;        for (int i = 2; i <= n; i++) {            temp=first+last;            first=last;            last=temp;        }        //返回        return temp;    }
0 0
原创粉丝点击