美文网首页
66. Plus One

66. Plus One

作者: exialym | 来源:发表于2016-09-21 22:49 被阅读27次

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

The digits are stored such that the most significant digit is at the head of the list.
这个就是想让你自己实现十进制加一咯,用一个进位来统一管理,各位加的一就假装是进上来的。

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

相关文章

网友评论

      本文标题:66. Plus One

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