Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

66. Plus One #247

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

66. Plus One

给定一个由 整数 组成的非空数组所表示的 非负 整数,在该数的基础上加一。

最高位数字存放在数组的首位, 数组中每个元素只存储 单个 数字。

你可以假设除了整数 0 之外,这个整数不会以零开头。

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.
Tcdian commented 4 years ago

Solution

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
    let carry = 1;
    const result = new Array(digits.length);
    for (let i = digits.length - 1; i >= 0; i--) {
        result[i] = (digits[i] + carry) % 10;
        carry = Math.floor((digits[i] + carry) / 10);
    }
    if (carry) {
        result.unshift(carry);
    }
    return result;
};
function plusOne(digits: number[]): number[] {
    let carry = 1;
    const result: number[] = new Array(digits.length);
    for (let i = digits.length - 1; i >= 0; i--) {
        result[i] = (digits[i] + carry) % 10;
        carry = Math.floor((digits[i] + carry) / 10);
    }
    if (carry) {
        result.unshift(carry);
    }
    return result;
};