[Sword refers to Offer learning] [interview question 9: Fibonacci series], offer Fibonacci
O (n) time O (1) Space implementation:
Public class Test09 {/*** write a function, input n, and calculate the Fibonacci (Fibonacci) number of entries in the number of columns * @ param n Fibonacci * @ return result of nth */public static long fibonacci (int n) {// if the input is not a positive integer, 0 if (n <= 0) {return 0;} is returned ;} // returns 1 if (n = 1 | n = 2) {return 1;} // returns the first two records (n-2) long prePre = 1; // the value of the first two (n-1) of the record long pre = 1; // the value of the first two (n-1) of the record (n) long current = 2; // returns the value of the number of Fibonacci for (int I = 3; I <= n; I ++) {// evaluate the value of the number of Fibonacci for the I-th current = prePre + pre; // update the record result, prePre originally recorded the value of the number of I-2-specific fiber ACCI // now recorded the value of the number of I-1-specific fiber ACCI prePre = pre; // updated the results of the record, pre originally recorded the value of the number of Fibonacci in the I-1 // now recorded the value of the number of I in the Fibonacci pre = current;} // return the expected result return current ;} public static void main (String [] args) {System. out. println (maid (0); System. out. println (maid (1); System. out. println (maid (2); System. out. println (maid (3); System. out. println (maid (4); System. out. println (maid (5); System. out. println (maid (6); System. out. println (maid (7 ));}}
Running result: