LeetCode #66 – Plus One

Here is my next problem:

Seems pretty easy, right? However, it gets a bit tricky with certain situations. Here are some examples:

While the first two examples are quite self-explanatory and seemingly easy, where the difficulty increases is with the last example. If digits = [9], then the method would return [1,0], which means you must make a new array and put the right numbers in, rather than simply adding one to the last digit. Here is how I effectively accomplished that:

This for loop above will start at the very back, and if the last digit is less than 9, it will increment the last element of digits by 1, and subsequently returns digits. However, if the last digit is 9, then it sets it to 0, and adds 1 to the rest of the digits. After that, you need to make sure you make a new array that has a length of digits.length + 1 and make the first digit 1. Here is what that looks:

Overall, here is what I ended up with:

Here is my output:

Here are the logistics for my solution:

Once again, faster than 100% of other Java solutions feels pretty good, and it is for the fourth time in a row! If you have any suggestions, be sure to let me know in the comments section below. I hope you guys at least learned something today and that you all have a great day!

By:

Posted in:


Leave a comment