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;
}