剑指offer--斐波那契数列

来源:互联网 发布:mysql触发器语法 编辑:程序博客网 时间:2024/06/03 19:45

题目描述

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。

分类:数组

解法1:根据前两项计算第三项,然后更新前两项即可。
[java] view plain copy
  1. public class Solution {  
  2.     public int Fibonacci(int n) {  
  3.         if(n==0return 0;  
  4.         if(n==1||n==2return 1;  
  5.         int pre  = 1;  
  6.         int next = 1;  
  7.         int t = 0;  
  8.         int i =2;  
  9.         while(i<n){  
  10.             t = pre+next;  
  11.             pre = next;  
  12.             next = t;  
  13.             i++;  
  14.         }         
  15.         return next;  
  16.     }  
  17. }  


原文链接  http://blog.csdn.net/crazy__chen/article/details/44986495

原创粉丝点击