简繁EN

LeetCodeNo. 098

[LeetCode with Python] 66. Plus One

Contents

Problem

Problem page: https://leetcode.com/problems/plus-one/
Topics: Array, Math
Difficulty: Easy
Similar problems: (M) Multiply Strings, (E) Add Binary

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.


Analysis

An int array represents a number, with the most significant digit on the left. Add 1 and return the result as an int array.
Just simulate addition and watch the carry. For numbers like 99 or 999, you also need to insert a 1 at the front of the array after adding 1.
The space complexity is O(1) whether or not there's a carry out of the most significant digit. The time complexity is O(N).


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
# @param digits, a list of integer digits
# @return a list of integer digits
def plusOne(self, digits):
len_s = len(digits)
carry = 1
for i in range(len_s - 1, -1, -1):
total = digits[i] + carry
digit = int(total % 10)
carry = int(total / 10)
digits[i] = digit
if 1 == carry:
digits.insert(0, 1)
return digits

Article link: https://xnerv.wang/en/leetcode-plus-one/