Fibonacci
2016-01-22 12:50
246 查看
Find the Nth number in Fibonacci sequence.
A Fibonacci sequence is defined as follow:
The first two numbers are 0 and 1.
The i th number is the sum of i-1 th number and i-2 th number.
The first ten numbers in Fibonacci sequence is:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 …
Have you met this question in a real interview? Yes
Example
Given 1, return 0
Given 2, return 1
Given 10, return 34
Note
The Nth fibonacci number won’t exceed the max value of signed 32-bit integer in the test cases.
A Fibonacci sequence is defined as follow:
The first two numbers are 0 and 1.
The i th number is the sum of i-1 th number and i-2 th number.
The first ten numbers in Fibonacci sequence is:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 …
Have you met this question in a real interview? Yes
Example
Given 1, return 0
Given 2, return 1
Given 10, return 34
Note
The Nth fibonacci number won’t exceed the max value of signed 32-bit integer in the test cases.
class Solution { /** * @param n: an integer * @return an integer f(n) */ public int fibonacci(int n) { if (n < 0) return -1; if (n == 1) return 0; if (n == 2) return 1; int fn = 0, fn1 = 1, fn2 = 0; for (int i = 3; i <= n; i++) { fn = fn1 + fn2; fn2 = fn1; fn1 = fn; } return fn; } }
相关文章推荐
- 相机和镜头选择时的一些参数
- Android 6.0 权限问题
- 发生android.view.ViewRoot$CalledFromWrongThreadException异常和loop循环的添加
- jQuery之基础选择器
- IO流 FileWriter 对已有文件的数据续写
- sublime Text3及其插件的使用
- 深入理解RunLoop
- Linux下防火墙开启相关端口及查看已开启端口
- apache commons io 最佳实践
- atime、mtime、ctime
- PHP,C# 和JAVARSA签名及验签
- Swift学习之泛型
- 算法训练 幂方分解
- 安卓开发中非常炫的效果集合
- 刘下记录:ImageView.scaleType 属性全解析(含视频)
- [从头学数学] 第56节 大数的认识
- Learning Java(2)——简介
- 用C++ 语言如何实现表达式拆分“1*2*3*(4+(5+6)*(7+8))+9”
- 快速排序算法
- Mac 下添加路径的办法,以及conda无法使用的解决办法