斐波那契数列JAVA实现- 返回前n个元素的数组

2019-03-18  本文已影响0人  早睡早起吃嘛嘛香

发现网上的都是返回第n个数的,
而不是数组,所以写了一个。
输入:n
输出:包含前n个元素的斐波那契数列数组


import java.util.Scanner;
import java.util.ArrayList;

public class Main {
    
    public static void main(String[] args) {
        Scanner sc = null;
        try {
             sc = new Scanner(System.in); 
             int n = sc.nextInt();
             ArrayList<Integer> fib = Fib(n);
             System.out.println(fib);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static ArrayList<Integer> Fib(int n){
        ArrayList<Integer> result =  new ArrayList<Integer>();
        for(int i = 0; i < n; i++){
            if( i == 0 || i == 1) {
                result.add(i);
            }
            else{
                int tmp = result.get(i-1)+result.get(i-2);
                result.add(tmp);
            }
        }
        
        return result;
    }  
}

上一篇下一篇

猜你喜欢

热点阅读