美文网首页
斐波那契数列【牛客网】

斐波那契数列【牛客网】

作者: 朱哥 | 来源:发表于2021-04-09 00:17 被阅读0次

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

    public class Solution {
        public int Fibonacci(int n) {
            if(n == 0) {
                return 0;
            }
            if(n == 1 || n == 2) {
                return 1;
            }
            int a2 = 1, a1 = 1;
            int result = 0;
            while(n > 2) {
                result = a2 + a1;
                --n;
                a1 = a2;
                a2 = result;
            }
            return result;
        }
    }
    

    相关文章

      网友评论

          本文标题:斐波那契数列【牛客网】

          本文链接:https://www.haomeiwen.com/subject/lhimkltx.html