1. 程式人生 > >劍指offer面試題10:斐波那契數列(Java 實現)

劍指offer面試題10:斐波那契數列(Java 實現)

題目:大家都知道斐波那契數列,現在要求輸入一個整數n,請你輸出斐波那契數列的第n項。
在這裡插入圖片描述

思路:使用遞迴會重複計算,效率較低,可以用迴圈自下到上計算。

測試用例:

  1. 功能測試:輸入3、5、10 等。
  2. 邊界測試:輸入0、1、2
  3. 效能測試:輸入較大的數(如40、50、100 等)。
public class test_ten {
	public int fibonacci(int n){
		int result = 0;
		int preOne = 1;
		int preTwo = 0;
		
		if(n==0)return preTwo;
		if(n==1)return preOne;
		
		for(int i=2; i<=n;i++){
			result = preOne + preTwo;
			preTwo = preOne;
			preOne = result;
		}
		return result;
	}
}