66.加一

作者: 最尾一名 | 来源:发表于2020-02-29 21:03 被阅读0次

原题

https://leetcode-cn.com/problems/plus-one/

解题思路

从数组的最后一位开始,一次加一,如果有进位的话取 10 的模,用 carry 表示进位
如果 carry === 0 或者到数组最前一位加一之后停止循环。
如果此时仍有进位,则往数组最前面添加数字 1。

代码

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
    if (!digits.length || !digits[0]) return [1];
    let carry = 1, currentIndex = digits.length - 1;
    while (carry && currentIndex >= 0) {
        carry = digits[currentIndex] + carry > 9 ? 1 : 0;
        digits[currentIndex] = (digits[currentIndex] + 1) % 10;
        --currentIndex;
    }
    if (currentIndex === -1 && carry) {
        digits.unshift(1);
    }
    return digits;
};

相关文章

  • 66. 加一

    给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 最高位数字存放在数组的首位, 数组中每个元素只...

  • 66. 加一

    文|Seraph 01 | 问题 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。最高位数字存放...

  • 66.加一

  • 66. 加一

    题目 给定一个非负整数组成的非空数组,给整数加一。 可以假设整数不包含任何前导零,除了数字0本身。 最高位数字存放...

  • 66.加一

    一、题目原型: 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。最高位数字存放在数组的首位, 数...

  • 66.加一

    题目给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 最高位数字存放在数组的首位, 数组中每个元...

  • 66. 加一

    给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。最高位数字存放在数组的首位, 数组中每个元素只存...

  • 66.加一

    原题 https://leetcode-cn.com/problems/plus-one/ 解题思路 从数组的最后...

  • 66. 加一

    https://leetcode-cn.com/problems/plus-one/

  • 66. 加一

    题目地址(66. 加一) https://leetcode.cn/problems/plus-one/[https...

网友评论

      本文标题:66.加一

      本文链接:https://www.haomeiwen.com/subject/autbhhtx.html