Created
December 27, 2017 08:22
-
-
Save miholeus/8a5ac18473893c6cff8ee75ff1bd4890 to your computer and use it in GitHub Desktop.
big numbers
This file contains hidden or 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 | |
$n1 = "1234534534534534534"; | |
$n2 = "3435435435353464362"; | |
// var_dump($n1+$n2); | |
function add($n1, $n2): string | |
{ | |
// ищем максимальное по длине число | |
if (strlen($n1) > $n2) { | |
$max = $n1; | |
$min = $n2; | |
} else { | |
$max = $n2; | |
$min = $n1; | |
} | |
// выравниваем строки | |
$min = str_pad($min, strlen($max), 0, STR_PAD_LEFT); | |
// складываем каждую цифру | |
$result = []; | |
$remainder = 0; | |
for($i=strlen($max)-1;$i>=0;$i--) { | |
$number = intval($max[$i])+intval($min[$i]); | |
$number += $remainder; | |
if ($number > 9) { | |
$remainder = intval(floor($number/10)); | |
$number = $number - 10; | |
} | |
$result[] = $number; | |
} | |
if ($remainder > 0) { | |
$result[] = $remainder; | |
} | |
return join("", array_reverse($result)); | |
} | |
var_dump(add($n1, $n2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment