7、斐波那契数列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NCUscienceZ/article/details/84260911

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39

public class Solution {
    public int Fibonacci(int n) {
        if (n == 1) return 1;
        if (n == 2) return 1;
        //return Fibonacci(n-1) + Fibonacci(n-2);
        int last1 = 1, last2 = 1, ans = 0;
        for (int i = 3; i<=n; i++){
            ans = last1+last2;
            last1 = last2;
            last2 = ans;
        }
        return ans;
    }
}

高中玩的水题~~
斐波那契数列1,1,2,3,5…

猜你喜欢

转载自blog.csdn.net/NCUscienceZ/article/details/84260911