oneby7

Math Number tricks

88. Plus One

Easy 147 DSA Sheet

You are given a non-negative integer written as an array digits. Each element is one decimal digit, and the most significant digit comes first, so [4, 0, 7] is the number 407.

Add one to the number and return the result as an array in the same form: one digit per element, most significant digit first, with no leading zeros.

Example 1

Input: digits = [6, 0, 9, 9]

Output: [6,1,0,0]

Explanation: The number is 6,099, and 6,099 + 1 = 6,100. The two 9s at the end become 0s, the 0 before them becomes a 1, and the 6 stays as it is.

Example 2

Input: digits = [9, 9, 9]

Output: [1,0,0,0]

Explanation: 999 + 1 = 1,000. The answer has one more digit than the input.

Example 3

Input: digits = [0]

Output: [1]

Explanation: The number 0 is written as [0], the only input that may start with a 0. Adding one gives 1.

Check your understanding

Work out the answer for this input before you write any code.

digits = [2, 9, 9]

Constraints

  • 1 ≤ digits.length ≤ 105
  • 0 ≤ digits[i] ≤ 9
  • digits has no leading zeros, except for the number 0 itself, which is [0].

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.