[LeetCode] Iterative and Recursive methods with Plus One problem

Khanh Vo
sharing and learning
3 min readAug 8, 2020

https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3382/

We come back with a problem which I think we also can learn and practice something new with Iterative and recursive. We will apply 2 ways in the same problem.

Now let’s get started with Iterative approach

This is not really hard an issue but to make it is more simple and how to find a good way to approach is not a simple thing.

The idea for this is really simple: you can find detail in here:https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3382/discuss/776400/Iterative-and-Recursive-with-Explanation

Take an example:

we have an array: 2, 3, 4, 5

1/ If the last value is NOT 9 we will immediately plus 1 for the last value and return the array

now our array will become: 2, 3, 4, 6

2/ but if the last value is 9, 9 + 1 = 10 and we take the value 0 and plus the 1 to the next value,

For instance, we have an array: 2, 3, 4, 9

so, in this case, we will be using the Else condition.

When the last value is updated to 0 and the for loop we move to the next element, and the value for the current element is 4.

Now the If the condition is true, and the 4 value will become 5 and immediately the array result will become: 2, 3, 5, 0

The last example: we have an array: 9, 9, 9 or just 9

is this case we expect the array result corresponding to 1, 0, 0, 0 or 1, 0

So we can observe that the size of the array will increase 1

So that is the reason we have 3 lines above of code

when we loop to the index 0 and we have the array will be 0, 0, 0 or 0

so the code will go out of the loop and we will create a new array with the size equal the digits.length + 1

and assign the 0 index value to 1.

Now we will move to the Recursive approach

take a look at plusOne(int[] digits, int index) we just need to mention the Else If condition.

In the “Else If” condition we will call recursive plusOne method until it meets the “If” or “Else” condition, and inside the plusOne method we just decrease the index by 1.

Conclusion, I think through this topic we can have a better understanding of Iterative and Recursive approach.

So that all for this topic. Hope that you can learn some new things from my sharing. Enjoy and Keep Learning!

--

--