Convert recursive algorithms into non-Recursive Algorithms

Source: Internet
Author: User

This week, a colleague was developing a function to convert a java object into a JSON string. I know there is an open-source jar package, but he said that it cannot handle his current needs, therefore, we need to develop a set of conversion methods. After reading the flowchart he painted, I could not understand it. I gave him some suggestions, drew a new flowchart, and implemented it recursively. I also gave him a suggestion to see if the recursive method can be implemented in non-recursive mode. The following is a simple column sub, which is implemented by non-recursive algorithms as a recursive algorithm.

Using java to calculate the factorial of an integer:

1. Recursive Algorithms for factorial

Static int factorial (int n ){
If (n> 1 ){
Return n * factorial (n-1 );
} Else if (n = 1 ){
Return 1;
}
Return 0;
}


2. Non-recursive algorithm for factorial
Static int factorial (int n ){
Stack <Integer> st = new Stack <Integer> ();
St. push (n );
Int temp;
Int total = 1;
While (temp = st. peek ())! = 1 ){
Total * = temp;
St. pop ();
St. push (temp-1 );
}
Return total;
}

Related Article

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.