LintCode地址:Fibonacci
题目中文摘要:
Require: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 ...
给定数字N,要求输出Fibonacci数列的第N项。第N项是第N-1项和第N-2项的和。
简单题,直接上代码了:
class Solution{
public:
/**
* @param n: an integer
* @return an integer f(n)
*/
int fibonacci(int n) {
// write your code here
int next = 0;
int a = 0;
int b = 1;
if (n == 1) {
return 0;
}
else if (n == 2) {
return 1;
}
else {
for (int i = 0; i<n - 2; i++) {
next = a + b;
if (i == n - 3) {
return next;
}
a = b;
b = next;
}
}
}
};