Search code examples
javascriptarraysiterationincrement

Given a non-empty array of digits representing a non-negative integer, increment one to the integer (javascript)


Was wondering if someone could explain the code solution to this problem. It's making no sense to me:

Given a non-empty array of digits representing a non-negative integer, increment one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.

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

The solution is as follows :

var plusOne = function(digits) {
    let carry = true
    for (let i = digits.length - 1; i >= 0; i -= 1) {
        if (digits[i] === 9 && carry) {
            digits[i] = 0;
            if (i === 0) {
                digits.unshift(1);
                break;
            }
        } else if (carry) {
            digits[i] += 1;
            carry = false;
        }
    }
    return digits;
};

I have a few questions about this solution :

  1. what is the purpose of the variable carry?
  2. why is digits[i] set to 0?
  3. why is there an if statement checking for (i===0)? And in turn, why is there a 1 added afterwards?

Any guidance would be appreciated, thanks!!


Solution

  • You have an array of integers where every element in the array is represents a digit of a number. Say you are given 456, then at index 0 you have 4, at index 1 you have 5 and at index 2 you have 6.

    Now, the problem asks you to add 1 to the given number.

    Here carry is mathematical carry that is used when you have to add two digits whose sum is greater than 10. By default we have carry as true because you are adding 1 to the number anyway. First you iterate(reverse) through the given digits and look for digits that are equal to 9 (carry being true), then change the current digit to zero and put 1 in the front. If carry is true and and the digit is not 9 then simply add 1 to the digit.

    examples :

    plusOne([4,9,7])
    (3) [4, 9, 8]
    

    here number 497 is given, and you just add 1 to the last digit.

    plusOne([1,4,9])
    (3) [1, 5, 0]
    

    here we see that the last digit is 9, so first we change it to zero then we add 1 to the second last digit.

    plusOne([9,9,9])
    (4) [1, 0, 0, 0]
    

    here we see that all the digit are 9, we change all digits to zero and add 1 in the beginning (this is where unshift 1 is used)