Q:

Write a PHP program to compute and print sum of two given integers (more than or equal to zero

0

Write a PHP program to compute and print sum of two given integers (more than or equal to zero). If given integers or the sum have more than 80 digits, print "overflow".

Pictorial Presentation:

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

 80) {
        echo "overflow\n";
        continue;
    }
    $arr = array_fill(0, 81, 0);
    $a = sprintf('%081s', $a);
    $b = sprintf('%081s', $b);
    for ($j = 80; $j > 0; $j--) {
        $n = $arr[$j] + $a[$j] + $b[$j];
        if ($n >= 10) {
            $arr[$j] = substr($n, 1);
            $arr[$j - 1] += 1;
        } else {
            $arr[$j] = $n;
        }
    }
    $result = preg_replace('/^0+(\d+)$/', '$1', implode('', $arr));
    if (strlen($result) > 80) {
        echo "overflow\n";
    } else {
        echo $result, PHP_EOL;
    }
}
?>

Sample Output:

46
overflow
overflow
overflow
overflow
...
overflow
overflow
overflow

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now