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