DEV Community

Zohaib Shahzad
Zohaib Shahzad

Posted on

The Walkthrough: Plus One (LeetCode 66)

Alt Text

If we’re given as an array the integer ‘123’, we simply want to increment the last digit and return the corresponding array representing that integer.
The first thing that should be pointed out is that we want to iterate via the given array backwards. A couple of edge cases that should be discussed is if the last digit of the number is ‘9’.

If we’re to encounter a case where the last digit of an integer value is ‘9’, then we set that index value to zero and then continue iterating. If not, then we’re working with a case where the last digit is anything but ‘9’ and in that case we simply increment that value of the digit and return the array of that integer.

Now if the last digits is a ‘9’. We simply set that digit to 0. The for loop will continue setting digits to ‘0’ if they’re ‘9’ and eventually will return the array. However, if we don’t return the array, that means we would have been dealing with a number that was for example: 9, 99, 999, 9999, etc. In that case, the array returned will contains all 0’s. The for loop will break in that case. We need to resize the array in that case.

Example: If we have 99, we return 100 which includes an extra digit.
When using languages like Java, we’ll have to resize the array if we’re to increment the last digit ‘9’.

Taking a look at line 9 above, that’s where we re-size the array if the last digit of the integer value is ‘9’. [digits.length + 1] basically says before our integer was ‘99’ and by adding an extra digit length to it, it now becomes ‘100’. We add one digit size to the array which then sets all values in the array to ‘0’ by default.

Direct your attention to line 11. Line 11 would be how we re-size the array in Javascript. Destructuring array’s have many benefits and but destructuring as a whole is an article for another day. [1, …digits] basically says we’re inserting a digit value of ‘1’ in front of whatever the rest of the integer value is.

Example: If we were dealing with [9, 9], we would end up increasing each digit value to [0, 0]. We would then add another placeholder of 1 to the beginning: [1, 0, 0].

Top comments (0)