Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.


You may assume the integer does not contain any leading zero, except the number 0 itself.


The digits are stored such that the most significant digit is at the head of the list.


Example 1:


Input: [1,2,3]

Output: [1,2,4]

Explanation: The array represents the integer 123.



Example 2:


Input: [4,3,2,1]

Output: [4,3,2,2]

Explanation: The array represents the integer 4321.



Let's start with the algorithm,


 const plusOne = digits => {

  for (let i = digits.length - 1; i >= 0; i--) {

    if (digits[i] === 9) {

      digits[i] = 0;

    } else {

      digits[i]++;

      return digits;

    }

  }

  digits.unshift(1);

  return digits;

};

console.log(plusOne([4,3,2,1]));

//[4,3,2,2]

console.log(plusOne([9,9,9,9]));

//[1,0,0,0,0]


Here, We have created a function where we will be passing array of integers and inside the function we have for loop which will be picking numbers one by one. But it is only checking last number to be 9, if last number is 9 then it will become 0 and next number will be incremented and if last number is not9 then last number of array is incremented.

If all the numbers in array are 9 then it will become 0 then we have unshift function outside for loop which add 1 by default in the array at first position.


I hope you understood the algorithm, let us know in the comment if you have any doubts.