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.

My code:

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
    let len = digits.length;
    if(digits[len - 1] != 9) { // 直接+1
        digits[len - 1]++
        return digits;
    } else if(len == 1) { // 一位9
        return [1, 0];
    } else {
        let carry = 1;
        for(let i = len - 1; i >= 0; i--) {
            if(digits[i] != 9) {
                carry = 0;
                digits[i]++;
            } else {
                digits[i] = 0;
            }
            if(carry == 0) { // 不是全部都为9
                return digits;
            }
        }
        return [1].concat(digits); // 全部都为9
    }
   
};

Note: 原来是用下面的代码的:

var plusOne = function(digits) {
    let formerInt = digits.reduce(function(a, b) {
       return '' + a + b;
   });
    let resultStr = (parseInt(formerInt) + 1).toString().split('');
    return resultStr.map(function(a) {
        return parseInt(a);
    });
};

submit的时候发现会出现原本结果应该是6145390195186705543,而代码结果为6145390195186705000的情况,自己试了下6145390195186705000 == 6145390195186705543的结果也是true,查了一下才发现大整数也存在精度问题,如果是超过2^53就会出现。

可以用代码来描述:

var x = 1; // 为了减少运算量,初始值可以设大一点,比如 Math.pow(2, 53) -10
while(x != x + 1) x++;
// x = 9007199254740992 即 2^53

Reference: Demon's Blog

你可能感兴趣的:(66. Plus One)