Skip to content

Instantly share code, notes, and snippets.

@KVytyagov
Created October 10, 2018 18:27
Show Gist options
  • Save KVytyagov/e7222cc8f028bbc938a322c4236a39f8 to your computer and use it in GitHub Desktop.
Save KVytyagov/e7222cc8f028bbc938a322c4236a39f8 to your computer and use it in GitHub Desktop.
Function to sum two integers in strings that bigger then PHP_INT_MAX
<?php
declare(strict_types=1);
function getLastIdx(string $strInt): int {
return '' === $strInt ? -1 : strlen($strInt) - 1;
}
function getDigitByIdx(string $strInt, int $idx): int {
return $idx >= 0 ? (int) $strInt[$idx] : 0;
}
function sumStrIntDigitIdx(string $strInt1, int $idx1, string $strInt2, int $idx2, int $remainder = 0): string {
if ($idx1 < 0 && $idx2 < 0) {
return 0 === $remainder ? '' : (string) $remainder;
}
$digit1 = getDigitByIdx($strInt1, $idx1);
$digit2 = getDigitByIdx($strInt2, $idx2);
$sum = $digit1 + $digit2 + $remainder;
$outDigit = $sum % 10;
$out = sumStrIntDigitIdx($strInt1, --$idx1, $strInt2, --$idx2, (int) ($sum / 10));
return $out . $outDigit;
}
function sumBigInt(string $a, string $b): string {
$aLastIdx = getLastIdx($a);
$bLastIdx = getLastIdx($b);
$out = sumStrIntDigitIdx($a, $aLastIdx, $b, $bLastIdx);
return '' === $out ? '0' : $out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment