Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

66. 加一 #5

Open
Geekhyt opened this issue Jan 22, 2021 · 0 comments
Open

66. 加一 #5

Geekhyt opened this issue Jan 22, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Jan 22, 2021

原题链接

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

数字 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 Geekhyt added the 简单 label Jun 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant