fork download
<?php
function compute($a, $b) {
if($b > $a) {
$c = $a;
$a = $b;
$b = $c;
}
$s = str_split($a);
$s2 = str_split($b);
$r = 0;
$lr = 0;
$temp = 0;
$value = "";
$j = count($s2) - 1;
for($i = (count($s) - 1); $i >= 0; $i--) {
if($j >= 0) {
$temp = $s[$i] + $s2[$j] + $lr;
if($temp > 9) {
$value .= substr($temp, -1);
$lr = substr($temp, 0, -1);
$r++;
}
else {
$value .= $temp;
}
$j--;
}
else {
$temp = $s[$i] + $lr;
if($temp > 9) {
$value .= substr($temp, -1);
$lr = substr($temp, 0, -1);
$r++;
}
else {
$value .= $temp;
}
}
}
if($lr != 0) { $value .= $lr; if($r > 1) {  --$r; } }
return "The sum of ".$a." and ".$b." is ".strrev($value)." and the carry out used to obtain this result is ".$r."\n";
}
echo compute(999, 1);
echo compute(1, 999);
echo compute(700, 9);
echo compute(987654321, 123456789);
echo compute(9, 9);
echo compute(9, 7);
echo compute(9, 1);
echo compute(20, 20);
?>
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
The sum of 999 and 1 is 1000 and the carry out used to obtain this result is 2
The sum of 999 and 1 is 1000 and the carry out used to obtain this result is 2
The sum of 700 and 9 is 709 and the carry out used to obtain this result is 0
The sum of 987654321 and 123456789 is 1111111110 and the carry out used to obtain this result is 8
The sum of 9 and 9 is 18 and the carry out used to obtain this result is 1
The sum of 9 and 7 is 16 and the carry out used to obtain this result is 1
The sum of 9 and 1 is 10 and the carry out used to obtain this result is 1
The sum of 20 and 20 is 40 and the carry out used to obtain this result is 0