劍指offer-9-斐波那契數列-java

xushiyu1996818發表於2020-11-05

題目及測試

package sword009;
/* 題目描述:寫一個函式,輸入n,求斐波那契數列的第n項,斐波那契數列的定義如下: 
 * n=0,f(n)=0 ;
 * n=1,f(n)=1 
 * n>1;f(n)=f(n-1)+f(n-2).

*/
public class main {
	
	public static void main(String[] args) {
		int[] testTable = {0,1,5,10};
		for (int i=0;i<testTable.length;i++) {
			test(testTable[i]);
		}
	}
		 
	private static void test(int ito) {
		Solution solution = new Solution();
		int rtn;
		long begin = System.currentTimeMillis();
		    System.out.print(ito+" ");
		    System.out.println();
		rtn = solution.fib(ito);//執行程式
		long end = System.currentTimeMillis();		
		    System.out.print(rtn+" ");
		System.out.println();
		System.out.println("耗時:" + (end - begin) + "ms");
		System.out.println("-------------------");
	}

}

解法1(成功)

可參考  https://blog.csdn.net/xushiyu1996818/article/details/82906181

package sword009;

public class Solution {
	public int fib(int n) {
		if(n <= 0) {
			return 0;
		}
		if(n == 1) {
			return 1;
		}
		if(n == 2) {
			return 1;
		}
		int n1 = 1; // n-1對應的值
		int n2 = 1;//  n-2對應的值
		int now = 0;
		for(int i=3;i<=n;i++) {
			now = n1+n2;
			n2 = n1;
			n1 = now;	
		}

		return now;

	}

}

 

 

相關文章