剑指Offer第七题:斐波那契数列

斐波那契数列

https://www.nowcoder.com/practice/c6c7742f5ba7442aada113136ddea0c3?tpId=13&tqId=11160&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
解答:
public class Q_7 {

public int Fibonacci(int n) {
    if (n <= 0) {
        return 0;
    }
    int fir = 1;
    int sec = 1;
    if (n == 1) {
        return fir;
    } else if (n == 2) {
        return sec;
    }
    int tmp = 0;
    for (int i = 2; i < n; i++) {
        tmp = fir + sec;
        fir = sec;
        sec = tmp;
    }
    return tmp;
}

public static void main(String[] args) {
    System.out.println(new Q_7().Fibonacci(10));
}

}

全部评论

相关推荐

点赞 评论 收藏
分享
09-03 17:49
已编辑
四川大学 供应链管理
迷茫的大四🐶:提前实习有些坑的,卡毕业后薪资以及能力不达预期提前违约这种
我的OC时间线
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务