Content-Length: 254198 | pFad | https://github.com/Geekhyt/javascript-leetcode/issues/5

33 66. 加一 · Issue #5 · Geekhyt/javascript-leetcode · GitHub
Skip to content

66. 加一 #5

@Geekhyt

Description

@Geekhyt

原题链接

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

数字 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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions









      ApplySandwichStrip

      pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


      --- a PPN by Garber Painting Akron. With Image Size Reduction included!

      Fetched URL: https://github.com/Geekhyt/javascript-leetcode/issues/5

      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy