javascript-leetcode icon indicating copy to clipboard operation
javascript-leetcode copied to clipboard

66. 加一

Open Geekhyt opened this issue 5 years ago • 0 comments

原题链接

加一,其实就是小学数学题,很简单,我们逐步来分析。

数字 9 加 1 会进位,其他的数字不会。

所以,情况无非下面这几种:

  1. 1 + 1 = 2 末位无进位,则末位加 1 即可。
  2. 299 + 1 = 300 末位有进位,首位加 1。
  3. 999 + 1 = 1000 末位有进位,最终导致前方多出一位,循环之外单独处理。
const plusOne = function(digits) {
    for (let i = digits.length - 1; i >= 0; i--) {
        if (digits[i] === 9) {
            digits[i] = 0
        } else {
            digits[i]++
            return digits
        }
    }
    digits.unshift(1)
    return digits
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

Geekhyt avatar Jan 22 '21 14:01 Geekhyt