面試題10- I. 斐波那契數列

題目:

面試題10- I. 斐波那契數列
509. 斐波那契數
在這裏插入圖片描述

題解:

在這裏插入圖片描述

代碼:

/**
 * 面試題10_1
 */
public class 面試題10_1 {

    public static int fib(int n) {
        if (n == 0 || n == 1) {
            return n;
        }
        int mod = 1000000007;
        int f1 = 0;
        int f2 = 1;
        int f3 = -1;
        for (int i = 2; i <= n; i++) {
            f3 = (f1 + f2) % mod;
            f1 = f2;
            f2 = f3;
        }
        return f3;
    }

    public static void main(String[] args) {
        System.out.println(fib(48));
    }
}

參考:

  1. 面試題10- I. 斐波那契數列
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章