Last active
December 16, 2015 13:28
-
-
Save SonkoDmitry/5441614 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 | |
function long_add($a, $b) | |
{ | |
//var_dump($a); | |
$a = explode('.', $a); | |
//var_dump($a); | |
//var_dump($b); | |
$b = explode('.', $b); | |
//var_dump($b); | |
$result = ''; | |
$result_dec = ''; | |
$razr = 0; | |
$razr_dec = 0; | |
if (strlen($a[0]) < strlen($b[0])) | |
$a[0] = str_repeat('0', strlen($b[0]) - strlen($a[0])) . $a[0]; | |
else if (strlen($b[0]) < strlen($a[0])) | |
$b[0] = str_repeat('0', strlen($a[0]) - strlen($b[0])) . $b[0]; | |
for ($i = strlen($a[0]) - 1; $i >= 0; $i--) { | |
$sum = intval($a[0][$i]) + intval($b[0][$i] + $razr); | |
if ($sum > 9) { | |
$razr = 1; | |
$sum = $sum - 10; | |
} else | |
$razr = 0; | |
$result = $sum . $result; | |
} | |
if ($razr === 1) | |
$result = $razr . $result; | |
if (isset($a[1]) && isset($b[1])) { | |
if (strlen($a[1]) < strlen($b[1])) | |
$a[1] = $a[1] . str_repeat('0', strlen($b[1]) - strlen($a[1])); | |
else if (strlen($b[1]) < strlen($a[1])) | |
$b[1] = $b[1] . str_repeat('0', strlen($a[1]) - strlen($b[1])); | |
/*var_dump($a[1]); | |
var_dump($b[1]);*/ | |
for ($i = strlen($a[1])-1; $i >= 0; $i--) { | |
//echo "sum ".intval($a[1][$i])."+".intval($b[1][$i])."=".(intval($a[1][$i]) + intval($b[1][$i]))."\n"; | |
$sum = intval($a[1][$i]) + intval($b[1][$i] + $razr_dec); | |
if ($sum > 9) { | |
$razr_dec = 1; | |
$sum = $sum - 10; | |
} else | |
$razr_dec = 0; | |
$result_dec = $sum . $result_dec; | |
} | |
if ($razr_dec === 1) | |
$result = $this->long_add($result, $razr_dec); | |
$j = strlen($result_dec); | |
/*var_dump($result_dec); | |
var_dump($j); | |
var_dump($result_dec[$j-1]);*/ | |
//die; | |
while ($j!=0 && $result_dec[$j-1] == '0') { | |
$j--; | |
} | |
//die; | |
if ($j===0) | |
$result_dec=''; | |
else | |
$result_dec=substr($result_dec,0,$j); | |
$result .= (strlen($result_dec) !== 0 ? '.' . $result_dec : ''); | |
} else if (isset($a[1])) | |
$result .= '.' . $a[1]; | |
else if (isset($b[1])) | |
$result .= '.' . $b[1]; | |
return $result; | |
} | |
var_dump($this->long_add('00.31','36.89')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment