366. 斐波纳契数列
2017-12-08 10:52
155 查看
描述:
查找斐波纳契数列中第 N 个数。
所谓的斐波纳契数列是指:
前2个数是 0 和 1 。
第 i 个数是第 i-1 个数和第i-2 个数的和。
斐波纳契数列的前10个数字是:
注意事项:
The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.
(翻译:在给出的测试案例中,第N个斐波那契数不会超出32位signed integer的最大取值范围)
样例
给定
给定
给定
思路:
初始值第一个斐波那契数是0,第二个是1,然后根据第一和第二个递推出后面的第N个。
Java代码:
查找斐波纳契数列中第 N 个数。
所谓的斐波纳契数列是指:
前2个数是 0 和 1 。
第 i 个数是第 i-1 个数和第i-2 个数的和。
斐波纳契数列的前10个数字是:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
注意事项:
The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.
(翻译:在给出的测试案例中,第N个斐波那契数不会超出32位signed integer的最大取值范围)
样例
给定
1,返回
0
给定
2,返回
1
给定
10,返回
34
思路:
初始值第一个斐波那契数是0,第二个是1,然后根据第一和第二个递推出后面的第N个。
Java代码:
1 public int fibonacci(int n) 2 { 3 if (n <= 0) return -1; 4 if (n == 1) return 0; 5 if (n == 2) return 1; 6 7 int n1 = 0; 8 int n2 = 1; 9 int target = 0; 10 11 for(int i = 3; i <= n; i++) 12 { 13 target = n1 + n2; 14 n1 = n2; 15 n2 = target; 16 } 17 18 return target; 19 }
相关文章推荐
- 366. 斐波纳契数列
- 【LintCode 入门】366. 斐波纳契数列
- LintCode_366_斐波纳契数列
- LintCode 366. 斐波纳契数列
- 366. 斐波纳契数列
- LintCode_366_斐波纳契数列
- LintCode_366_斐波纳契数列
- Lintcode 入门-366斐波纳契数列
- 【LintCode-366】斐波纳契数列 (Java实现)
- 斐波纳契数列!
- NYOJ366 D的小L 和 NYOJO32 组合数 和 NYOJ19 擅长排列的小明 和 NYOJ488 素数环 【递归】
- NYOJ 366 D的小L
- 斐波纳契数列
- PHP上台阶问题(斐波纳契数列应用)
- 用PHP迭代器来实现一个斐波纳契数列
- CodeForces 366B - Dima and To-do List
- Java算法求最大最小值,倒序,冒泡排序,斐波纳契数列,日历一些经典算法
- 【南理oj】366 - D的小L(STL - 全排列)
- 【ny-oj】-366-D的小L(STL-全排列(next_permutation()))
- 查找斐波纳契数列中第 N 个数