Plus One
Easy · Math & Geometry
You are given a large non-negative integer represented as a list of its digits, most significant digit first. Add one to the number and return the resulting digits in the same order. The input never has leading zeros unless the number itself is zero.
Examples
Input: digits = [1,2,3]
Output: [1,2,4]
Why: 123 + 1 = 124, so the digits become 1,2,4.
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Why: 4321 + 1 = 4322.
Input: digits = [9,9]
Output: [1,0,0]
Why: 99 + 1 = 100, which needs an extra leading digit.
Constraints
1 <= digits.length <= 10^4, 0 <= digits[i] <= 9, and digits has no leading zero except possibly a single digit 0
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Plus One. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.