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的時候發(fā)現(xiàn)會出現(xiàn)原本結(jié)果應(yīng)該是6145390195186705543,而代碼結(jié)果為6145390195186705000的情況,自己試了下6145390195186705000 == 6145390195186705543的結(jié)果也是true,查了一下才發(fā)現(xiàn)大整數(shù)也存在精度問題,如果是超過2^53就會出現(xiàn)。
可以用代碼來描述:
var x = 1; // 為了減少運(yùn)算量,初始值可以設(shè)大一點(diǎn),比如 Math.pow(2, 53) -10
while(x != x + 1) x++;
// x = 9007199254740992 即 2^53
Reference: Demon's Blog