Java Interview: Rabbit problem

Source: Internet
Author: User

To solve this problem to note: Find the recursive method body, recursive export.

Package com.cc; /**
*
* There are a pair of rabbits, from the third month after the birth of a pair of rabbits each month, the rabbit long to the third month after the birth of a pair of rabbits each month, if the rabbit is not dead, ask the total number of rabbits each month.
* @author liukeqing
*
*/
public class Hello {

public static void Main (string[] args) {
int month = 8;//first few months
int sum = getcount (month);//Get the total number of rabbits this month
System.out.println ("The first" +month+ "Month born Rabbit:" +sum + "only");
}
The design idea of recursive algorithm: for a complex problem, the original problem is decomposed into several relatively simple and identical sub problems. Continue until the child problem is simple enough to be solved directly.
/**
* Get the total number of bunnies = The total number of rabbits + newborn rabbit total = last month (n-1) The total number of rabbits + last month (n-2) The total number of rabbits
* @param month the first few months
* @return
*/
private static int getcount (int month) {
int sum = 0;//monthly Rabbit Total
if (month = = 1 | | month ==2) {//The first month and the second month of each pair of rabbits are barren, the rabbits are a pair
sum = 2;
}else{//Rabbit begins to bear
sum = GetCount (month-1) + GetCount (month-2);
}
return sum;
}
}

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.