InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Math & Geometry

Plus One

easy Original ↗ 00:00

Problem

You are given a non-negative integer represented as a list of its decimal digits digits, most-significant digit first. The number has no leading zeros (except the number 0 itself, given as [0]). Add one to the number and return the resulting list of digits.

Examples

  • digits = [1, 2, 3][1, 2, 4] — 123 + 1 = 124.
  • digits = [4, 3, 9][4, 4, 0] — 439 + 1 = 440; the trailing 9 rolls over and carries.
  • digits = [9, 9][1, 0, 0] — 99 + 1 = 100; the carry propagates off the front, growing the array.

Constraints

  • 1 <= len(digits) <= 100
  • 0 <= digits[i] <= 9
  • digits has no leading zeros (aside from [0]).

Think about it first

Hint 1 Adding one only affects the end of the number, and it only keeps rippling left while it hits digits equal to 9 (which become 0 and pass a carry along).
Hint 2 Walk from the last digit toward the first. The first digit less than 9 can be incremented, and you're done — every digit to its right stays as it is.
Hint 3 The only case where the array grows is all-nines: they all become 0 and you must prepend a leading 1, turning `[9,9,9]` into `[1,0,0,0]`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug