Fibonacci
题目:
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 ...
补充: (2016-10-30) 特殊处理一个情况就是第1个和第2个fib的情况。长期不coding忘记了特殊情况的重要性
分析:
看题意,特别注意0,1,2,3时候的输入
解法:
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;
}
if (n == 1) {
return 1;
}
int a = 0;
int b = 1;
for (int i = 2; i <= n; i++) {
int temp = a + b;
b = a;
a = temp;
}
return a;
}
}