Search code examples
javascriptarraysfor-loopincrement

Given an array of integers ‘num’ return the array incremented by 1


Given an array of integers, return a new array that has that original values incremented by 1.

Each value in the array can't exceed 9 and you can't use any function that converts the array into an integer.

i.e:

Original Array = [1,2,7,9]
Returned Array = [2,3,8,0]

@param (array) num
@return (array)

This is what I am currently doing. Just wondering if there is anything that will be more efficient.

function increment (num) {
    for (var i = num.length - 1; i >= 0; i--) {
        num[i]++;
        if (num[i] > 9) num[i] = 0;
        else break;
    }
    return num;
}

console.log(increment([1, 2, 7, 9]));

Solution

  • There's one problem: if the input array is composed of all 9s, you want a desired output of, eg, [1, 0, 0, 0, 0] (rather than [0, 0, 0, 0]):

    function increment (num) {
        for (var i = num.length - 1; i >= 0; i--) {
            num[i]++;
            if (num[i] > 9) {
              num[i] = 0;
              if (i === 0) {
                // Last iteration, but we need to carry - unshift a 1:
                num.unshift(1);
              }
            }
            else break;
        }
        return num;
    }
    
    
    console.log(increment([1, 2, 7, 9]));
    console.log(increment([3, 9, 9, 9]));
    console.log(increment([9, 9, 9, 9]));
    console.log(increment([1, 1, 1, 1]));