Created
January 22, 2019 13:09
-
-
Save zeromodule/9e0b78c007adac149308d9073da0f157 to your computer and use it in GitHub Desktop.
Сложение столбиком
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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