剑指offer JZ7 斐波那契数列
发布日期:2021-05-07 10:44:57 浏览次数:23 分类:精选文章

本文共 469 字,大约阅读时间需要 1 分钟。

JZ7题目链接:本题思路:

本题要求编写一个计算斐波那契数列的函数。题目给出的代码实现思路如下:

代码实现思路:

  • 定义两个初始变量first和second分别表示斐波那契数列的第0项和第1项
  • 初始化current变量用于存储当前计算的斐波那契数
  • 使用一个循环从1到n-1进行迭代
  • 在每次循环中,计算current为first和second的和
  • 更新first和second的值,使其分别取第二个和当前的值
  • 当循环结束后返回current值
  • 代码实现:

    public class Solution {

    public int Fibonacci(int n) {
    if(n == 0 || n == 1) return n;
    int first = 0;
    int second = 1;
    int current = 0;
    for(int i = 1; i < n; i++) {
    current = first + second;
    first = second;
    second = current;
    }
    return current;
    }
    }

    上一篇:剑指offer JZ8 跳台阶
    下一篇:二叉树 简单实现 问题解决

    发表评论

    最新留言

    哈哈,博客排版真的漂亮呢~
    [***.90.31.176]2025年04月01日 14时38分51秒