66. Plus One

Published: (January 1, 2026 at 08:01 AM EST)
1 min read
Source: Dev.to

Source: Dev.to

Problem Description

You are given a large integer represented as an integer array digits, where each digits[i] is the iᵗʰ digit of the integer. The digits are ordered from most significant to least significant (left‑to‑right). The integer does not contain any leading zeros.

Task: Increment the integer by one and return the resulting array of digits.

Examples

InputOutputExplanation
digits = [1,2,3][1,2,4]123 + 1 = 124
digits = [4,3,2,1][4,3,2,2]4321 + 1 = 4322
digits = [9][1,0]9 + 1 = 10

Constraints

  • 1 = 0; $i--) {

Solution (PHP)

<?php
function plusOne(array $digits): array {
    $carry = 1;
    for ($i = count($digits) - 1; $i >= 0; $i--) {
        $sum = $digits[$i] + $carry;
        $digits[$i] = $sum % 10;
        $carry = intdiv($sum, 10);
        if ($carry === 0) {
            break; // no further propagation needed
        }
    }
    if ($carry === 1) {
        array_unshift($digits, 1);
    }
    return $digits;
}

// Test cases
print_r(plusOne([1, 2, 3]));   // [1, 2, 4]
print_r(plusOne([4, 3, 2, 1])); // [4, 3, 2, 2]
print_r(plusOne([9]));          // [1, 0]
?>
Back to Blog

Related posts

Read more »

1390. Four Divisors

Problem Statement Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such in...

Day 0: Starting My DSA Journey

Day 0 – Planning, Mindset & Commitment - Goal: Become strong in problem‑solving & interview‑ready - Starting level: Beginner / Revising basics - Daily commitme...