查找斐波纳契数列中第 N 个数。
所谓的斐波纳契数列是指:
- 前2个数是 0 和 1 。
- 第 i 个数是第 i-1 个数和第i-2 个数的和。
斐波纳契数列的前10个数字是:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
class Solution {
/**
* @param n: an integer
* @return an integer f(n)
*/
public int fibonacci(int n) {
// write your code here
if (n == 1){
return 0;
}
else if (n == 2){
return 1;
}
//注释掉的是递归的做法 递归会出现超时问题
//else
// return fibonacci(n-1)+fibonacci(n-2);
int a = 0;
int b = 1;
int result = 0;
int i = 3;
while (i <= n ){
result = a + b;
a = b;
b = result;
i++;
}
return result;
}
}