斐波那契数列

斐波那契数列

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

代码实现

package 剑指offer;

/**
 * @author WangXiaoeZhe
 * @Date: Created in 2019/11/22 15:17
 * @description:
 */

public class Main5 {
    public static void main(String[] args) {

    }
    /**
     * 递归
     *
     * @param n
     * @return
     */

    public static int f1(int n) {
        if (n <= 2) {
            return 1;
        } else {
            return f1(n - 1) + f1(n - 2);
        }
    }

    /**
     * 非递归
     */

    public static int f2(int n) {
        int a1=1;
        int b2=1;
        int c3=0;
        for (int i=2;i<=n;i++){
            c3=a1+b2;
            a1=b2;
            b2=c3;
        }
        return c3;
    }
}
posted @ 2019-11-22 15:21  π。  阅读(238)  评论(0编辑  收藏  举报