本文参考自《剑指offer》一书,代码采用Java语言。

更多:《剑指Offer》Java实现合集  

题目

  写一个函数,输入n,求斐波那契(Fibonacci)数列的第n项。

【Java】 剑指offer(9) 斐波那契数列及青蛙跳台阶问题

思路

  如果直接写递归函数,由于会出现很多重复计算,效率非常底,不采用。

  要避免重复计算,采用从下往上计算,可以把计算过了的保存起来,下次要计算时就不必重复计算了:先由f(0)和f(1)计算f(2),再由f(1)和f(2)计算f(3)……以此类推就行了,计算第n个时,只要保存第n-1和第n-2项就可以了。

测试用例

  1.功能测试(3,5,8等)

  2.边界值测试(0,1,2等)

  3.性能测试(50,100等)

  4.特殊(负数)

完整Java代码

(含测试代码)

/**
 * 
 * @Description 斐波那契数列
 *
 * @author yongh
 * @date 2018年9月13日 下午7:19:36
 */

// 题目:写一个函数,输入n,求斐波那契(Fibonacci)数列的第n项。

public class Fibonacci {
	public long Fib(long n) {
		if(n<0)
			throw new RuntimeException("下标错误,应从0开始!");
		if (n == 0)
			return 0;
		if (n == 1)
			return 1;
		long prePre = 0;
		long pre = 1;
		long result = 1;
		for (long i = 2; i <= n; i++) {
			result = prePre + pre;
			prePre = pre;
			pre = result;
		}
		return result;
	}
	
	//附:缩略版(考虑到代码的可读性,其实还是上面的方法比较好)
	public long Fib2(long n) {
		if(n<0)
			throw new RuntimeException("下标错误,应从0开始!");
		if (n == 0)
			return 0;
		if (n == 1)
			return 1;
		long pre = 0;
		long result = 1;
		for (long i = 2; i <= n; i++) {
			result += pre;
			pre = result - pre;
		}
		return result;
	}

	public static void main(String[] args) {
		Fibonacci demo = new Fibonacci();
		System.out.println(demo.Fib(0));
		System.out.println(demo.Fib(1));
		System.out.println(demo.Fib(2));
		System.out.println(demo.Fib(8));
		System.out.println(demo.Fib(50));
		System.out.println(demo.Fib(100));
		System.out.println(demo.Fib(-5));
	}
}

  

0
1
1
21
12586269025
3736710778780434371
Exception in thread "main" java.lang.RuntimeException: 下标错误,应从0开始!
Fibonacci

相关文章:

  • 2021-06-20
  • 2022-12-23
  • 2021-09-13
  • 2021-08-21
  • 2022-12-23
  • 2021-05-16
  • 2021-04-10
猜你喜欢
  • 2022-12-23
  • 2022-03-03
  • 2022-12-23
  • 2022-12-23
  • 2021-12-25
  • 2022-12-23
相关资源
相似解决方案