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

LeetCode题解:66. 加一,倒序遍历+可中途退出,JavaScript,详细注释 #134

Open
chencl1986 opened this issue Aug 20, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

chencl1986 commented Aug 20, 2020

原题链接:https://leetcode-cn.com/problems/plus-one/

解题思路:

  1. 倒序遍历当前数组,对当前位加1。
  2. 如果当前位之和为10,设置当前位为0,下一位继续加1操作。
  3. 如果当前位之和小于10,后续位数不需要操作,直接退出循环。
  4. 如果正常完成循环,表示最后一位之和为10,则需要在digits第一位之前增加一位为1。
/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function (digits) {
  // 倒序遍历数组
  for (let i = digits.length - 1; i >= 0; i--) {
    // 对当前位进行加1操作,如果结果为10,则表示需要进位,需要把当前位置为0
    if (++digits[i] >= 10) {
      digits[i] = 0;
    } else {
      // 如果当前不需要进位,则之后的位数也不需要继续操作,直接返回结果
      return digits;
    }
  }

  return [1, ...digits];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant