LeetCode: Add Two Numbers and Using Static Blocks to Help print Recursive Solutions

I ran into a problem doing a LeetCode challenge in Java the other day. I could see that the solution was best solved with recursion, but I wasn’t exactly sure how to print the solution as the recursive method was executing. I remembered that using a static block in a Java class makes it so that any time a class is loaded in the JVM, the code inside that block will execute. Because LeetCode uses a Solution class for their problem templates, I simply added the code inside this block to initialize the first part of the solution’s output. I then continued the output with every iteration of the recursion. Below is the code I used:

This quick-and-easy trick is great for printing out the results of recursive methods written in Java as they are executing in LeetCode. Instead of returning a result from a recursive method and using that to print something to the console, we use a static block to begin the process of printing something to the console before the first recursive step even begins to execute, and we continue to print with every iteration of the recursion, finally terminating the output with the base case of the recursive method.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: