手写代码之写斐波那契数列-传入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);
    }

  

猜你喜欢

转载自www.cnblogs.com/qianjinyan/p/11185166.html
0条评论
添加一条新回复