斐波那契数列

2020-02-29  本文已影响0人  冉桓彬
循环
public int test(int index) {
    if (index == 0) {
        return 0;
    }
    if (index == 1 || index == 2) {
        return 1;
    }
    int current = 0;
    int ppre = 1;
    int pre = 1;
    for (int i = 3; i < n ; i++) {
        current  = pre + ppre;
        ppre = pre;
        pre = current;
    }
    return current;
}
递归
public int test(int n) {
    if (n ==1 || n == 2) {
        return 1;
    }
    return test(n-1) + test(n-2);
}
上一篇 下一篇

猜你喜欢

热点阅读