Posted by : Mostafa Mazhar

Problem Name : Plus One

Platform : leetcode

Language: Javascript

Link : Plus One


In this problem you have a number which represented by an array where every element of the array represents a digit of the number,  for example the number 123 is represented as [1 , 2 , 3].


You are required to increase the given number by 1 and return it as an array.

 

So your gonna add one to the last element of the array and boom you solved the problem..... well if you do that and submit your answer you will get an error because if the last digit is 9 say the number is [1 , 2 ,  9] and increased by 1 it will be [1 , 2 , 10]  instead of  [1 , 3 , 0]. in that case i we found that the last digit is 9 we gonna make it  0 and increase the next digit by one and we good to go..



Oops.. you get another error😐😂.  because if we get a number that the next digit is also 9 say 1299, we will get the same problem but on a different digit this time, the solution is simple we need to loop through the digits and do the last step on every one of them.


Well we still have a little problem here if we got a number that all of it's digits is 9s say 99, according to our code the answer will be 00 , and the solution to that is to make the firist digit 1 and add 0 to the back of the array.


Enough talking and let's dive to the algorithm:

  • loop through the array starting from the last element(firist digit).
  • Creat an if statment inside the for loop, if the digit is not 9 we increase it by 1 and break (exit) the for loop.
  • If it's 9 we make it 0 and repeat the steps on the next digit until we break the loop.
  • The last step is to check if the first elemnt of the array is 0 we make it 1 and push 0 in the back of the array.


And  yay✌












Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © 2025 Quarks - Blogger Templates - Powered by Blogger - Designed by Johanes Djogan -