Skip to content

66. Plus One

https://leetcode.com/problems/plus-one/

js
/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
  digits[digits.length - 1] += 1

  for (let i = digits.length - 1; i >= 0; i--) {
    if (digits[i] >= 10) {
      digits[i] -= 10
      if (i === 0) {
        digits.unshift(1);
      } else {
        digits[i - 1] += 1
      }
    } else {
      return digits
    }
  }

  return digits
}
py
class Solution(object):

    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        digits[- 1] += 1
        for i in reversed(range(len(digits))):
            if digits[i] >= 10:
                digits[i] -= 10
                if i == 0:
                    digits = [1] + digits
                else:
                    digits[i - 1] += 1
            else:
                return digits
        return digits