斐波那契数列
2016-06-20 23:56
204 查看
题目
要求输入一个整数n,请你输出斐波那契数列的第n项。解题
方法一:递归public class Solution { public int Fibonacci(int n) { if(n <=0) return 0; if(n==1) return 1; if(n==2) return 1; return Fibonacci(n-1) + Fibonacci(n-2); } }
溢出
方法二:循环
public class Solution { public int Fibonacci(int n) { int f0 = 0; int f1 = 1; int f2 = 1; if(n <=0) return f0; if(n==1) return f1; while(n>=2){ f2 = f0 + f1; f0 = f1; f1 = f2; n--; } return f1; } }
相关文章推荐
- Eclipse快捷键大全
- 切身体会,debug与release的区别
- al实验
- Python爬虫实践(六):正则表达式(1)
- UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position xxx ordinal not in range解决方安
- Java基础
- Exynos4412 NFS服务器搭建
- 柴俊理金:6、20午夜黄金,宁贵沥青操作策略
- 线程的生命周期以及java提供的方法
- 跨平台XMPP企业即时通信系统开发基础
- Struts2学习(二)--使用struts2编写helloworld
- 简单Makefile编写
- AS自动导入 auto import
- px4开发文档的翻译搬到github和gitbook了
- 控制反转、依赖注入的实质
- [WEB]PHP的编码 与MySQL5.5的编码 适配
- LeetCode200—Number of Islands
- [转]海量存储检索原理系列文章
- Python验证码识别
- 计量金融学