[Sword refers to Offer learning] [interview question 9: Fibonacci series], offer Fibonacci

Source: Internet
Author: User

[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:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.