Skip to content

Instantly share code, notes, and snippets.

@zeromodule
Created January 22, 2019 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeromodule/9e0b78c007adac149308d9073da0f157 to your computer and use it in GitHub Desktop.
Save zeromodule/9e0b78c007adac149308d9073da0f157 to your computer and use it in GitHub Desktop.
Сложение столбиком
<?php declare(strict_types=1);
/**
* Сложение "столбиком"
*/
function sum(string $a, string $b): string
{
$args = func_get_args();
foreach ($args as $key => $val) {
if ($val[0] === '0' || !preg_match('/^\d+$/', $val)) {
throw new InvalidArgumentException(sprintf('Аргумент %d не является представлением целого положительного числа', $key));
}
}
if (strlen($b) > strlen($a)) {
$tmp = $a;
$a = $b;
$b = $tmp;
}
$a = strrev($a);
$b = strrev($b);
$a_len = strlen($a);
// десятки "в уме"
$d = 0;
$result = '';
for ($i = 0; $i < $a_len; $i++) {
$b_value = isset($b[$i]) ? (int)$b[$i] : 0;
$sum = (int)$a[$i] + $b_value + $d;
$d = ($sum < 10) ? 0 : 1;
$result .= $d ? $sum - 10 : $sum;
}
$result .= $d ?: '';
return strrev($result);
}
echo sum('999', '9991') . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment