当前位置:网站首页>算法--斐波那契数列(Kotlin)
算法--斐波那契数列(Kotlin)
2022-07-27 05:45:00 【小米科技Android 研发曹新雨】
题目
写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项(即 F(N))。斐波那契数列的定义如下:
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:n = 2
输出:1
示例 2:
输入:n = 5
输出:5
提示:
0 <= n <= 100
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/fei-bo-na-qi-shu-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解决方法
fun fib(n: Int): Int {
if (n < 2) {
return n
}
var pre_pre = 0
var pre = 1
var result = 0
for (i in 2..n) {
result = (pre + pre_pre) % 1000000007
pre_pre = pre
pre = result
// println("$pre $pre_pre")
}
return result
}
总结
1.取模这里还是没有思考明白 数字太大相加可能会导致溢出int范围为负数
所以一定要清楚
2.斐波那契数列真的是动态规划的鼻祖
边栏推荐
- jest单测样式问题【identity-obj-proxy】npm包
- 线性表 -- 栈和队列
- Dajiang livox customized format custommsg format conversion pointcloud2
- CdS quantum dots modified DNA | CDs DNA QDs | near infrared CdS quantum dots coupled DNA specification information
- 肽核酸PNA-多肽PNA-TPP|Glt-Ala-Ala-Pro-Leu-pNA|Suc-Ala-Pro-pNA|Suc-AAPL-pNA|Suc-AAPM-pNA
- Ci framework learning of PHP
- Livox SLAM(带LIO+闭环检测优化)
- nvidia-smi 各参数意义
- Shell编程的规范和变量
- ESP8266(ESP-12F) 第三方库使用 -- SparkFun_APDS9960 (手势识别)
猜你喜欢

Web configuration software for industrial control is more efficient than configuration software

Reasoning speed of model

Watermelon book learning Chapter 5 --- neural network

Using docker to install and deploy redis on CentOS

AI:业余时间打比赛—挣它个小小目标—【阿里安全×ICDM 2022】大规模电商图上的风险商品检测比赛

Mysql database

硫化镉CdS量子点修饰脱氧核糖核酸DNA|CdS-DNA QDs|近红外CdS量子点偶联DNA规格信息

DNA(脱氧核糖核酸)供应|碳纳米管载核酸-DNA/RNA材料|DNA/RNA核酸修饰磁性纳米颗粒

Fix the problem that the paging data is not displayed when searching the easycvr device management list page

ZnS-DNA QDs近红外硫化锌ZnS量子点改性脱氧核糖核酸DNA|DNA修饰ZnS量子点
随机推荐
Details of cross entropy loss function in pytorch
jest单测样式问题【identity-obj-proxy】npm包
Web configuration software for industrial control is more efficient than configuration software
李沐动手学深度学习V2-transformer和代码实现
Variance and covariance
Norms of vectors and matrices
MySQL的基本语句(1)—增删改查
Qi Yue: thiol modified oligodna | DNA modified cdte/cds core-shell quantum dots | DNA coupled indium arsenide InAs quantum dots InAs DNA QDs
Basic statement of MySQL (1) - add, delete, modify and query
Common problems in converting pytorch to onnx
Summary of APP launch in vivo application market
OpenGL development with QT (I) drawing plane graphics
Boostrap
基于SSM实现的校园新闻发布管理系统
String类的用法
How to make the minimum API bind the array in the query string
ESP8266(ESP-12F) 第三方库使用 -- SparkFun_APDS9960 (手势识别)
Analysis of pix2pix principle
工控用Web组态软件比组态软件更高效
Event capture and bubbling - what is the difference between them?