手写代码之写斐波那契数列-传入key值求对应的value

public class Testany {
 
    public static void main(String[] args) {
        int value = number(10);
        System.out.println(value);
    }
 
    public static int number(int k){
        int value = 0;
        int a = 1;
        int b = 1;
        for(int i =1; i<=k;i++){
            value= a+b;
            a = b;
            b= value;
        }
        return  value;
 
    }
}

  

public static void main(String[] args) {
        int value = Fun(10);
        System.out.println(value);
    }
 
    public static int Fun(int k){
        int arr[] = new int[k];
        arr[0] = arr[1] = 1;
        for (int i = 2; i < arr.length; i++) {
            arr[i] = arr[i - 1] + arr[i - 2];
        }
        return arr[k-1];
    }

  

最简单写法

public static void main(String[] args) {
        System.out.println(getFibo(10));
    }
 
    private static int getFibo(int i) {
        if (i == 1 || i == 2)
            return 1;
        else
            return getFibo(i - 1) + getFibo(i - 2);
    }

  

posted @ 2019-07-14 18:39  巴黎爱工作  阅读(374)  评论(0编辑  收藏  举报