66. Plus One
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
| Input | Output | Explanation |
|---|---|---|
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]
?>