Task 1: Array Form Compute
"Adding Digits Like a Pro: Big Integer in Disguise!"
Given an array of digits representing a number (most significant digit first) and an integer x, add x to the number and return the result as an array of digits.
The Strategy: Process digits from right to left, adding x as the carry. For each position, compute sum = carry + digit, store sum % 10 as the result, and carry = sum / 10. Continue while there are digits remaining or carry is non-zero. This naturally handles arbitrarily large arrays.
Perl Implementation
sub array_form_compute ( $digits_ref, $x ) {
my @digits = $digits_ref->@*;
my @result;
my $index = $#digits;
my $carry = $x;
while ( $index >= 0 || $carry > 0 ) {
my $sum = $carry;
if ( $index >= 0 ) {
$sum += $digits[$index];
$index--;
}
unshift @result, $sum % 10;
$carry = int( $sum / 10 );
}
return @result ? @result : (0);
}
Python Implementation
def array_form_compute(digits: list[int], x: int) -> list[int]:
"""Add integer x to the array-form representation of a number."""
result = []
index = len(digits) - 1
carry = x
while index >= 0 or carry > 0:
total = carry
if index >= 0:
total += digits[index]
index -= 1
result.append(total % 10)
carry = total // 10
return list(reversed(result)) if result else [0]