66. Plus One

Description

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

You may assume the integer do 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.

Solution

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
    let carry = 1;
    for (let i = digits.length-1; i >= 0; i--) {
        digits[i] = digits[i] + carry;
        if (digits[i] === 10) {
            digits[i] = 0;
            carry = 1;
        } else {
            carry = 0;
        }
    }
    if (carry) {
        digits.unshift(1);
    }
    return digits;
};

results matching ""

    No results matching ""