斐波那契玩耍

160 阅读1分钟
/*
* 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)。

n≤39n\leq 39n≤39
*
* */
public class Fibo {

    public static void main(String[] args) {

        int n = 5;
        int number = Fibonacci(n);
        System.out.println(number);
    }

    //递归解法速度很慢
//    public static int Fibonacci(int n){
//        int k = n;
//        if (k == 0){
//            return 0;
//        }else if (k == 1){
//            return 1;
//        }else if (k > 1){
//            return Fibonacci(n -1)+ Fibonacci(n - 2);
//        }else {
//            return Integer.parseInt(null);
//        }
//    }

    public static int Fibonacci(int n){

        if (n == 0){
            return 0;
        }else if (n == 1){
            return 1;
        }else if(n > 1){
            int a = 1;
            int b = 0;

            int result = 0;

            for (int i = 0; i < n - 1; i++) {
                result = a + b;
                b = a;
                a = result;
            }

            return result;
        }else {
            return Integer.parseInt(null);
        }
    }
}