SprintCode.pro

Подготовка к алгоритмическим задачам

Super

Plus One

Description: A number is represented as an array of digits, most significant first. Add one and return the result in the same form.

Example 1:

Input: digits = [1,2,3]
Output: [1,2,4]

Example 2:

Input: digits = [9,9]
Output: [1,0,0]

Constraints:

1 <= digits.length <= 100

0 <= digits[i] <= 9

Ведущих нулей нет

Recommended time and space complexity

O(n) time.


Hint 1

Walk from the end of the array — that is the least significant digit.


Hint 2

If a digit is less than nine, increment and return immediately.


Hint 3

If all digits are nines, the result is one element longer.

A digit-array arithmetic problem. Teaches carry handling and the case where the result grows longer.

Expected Input :

[1,2,3]

Expected Output

[1,2,4]