Big Integer Addition
PHP
Hard
4 views
Problem Description
Two big non-negative integers are given as strings. Print their sum.
Input Format
One line: a b.
Output Format
One integer string.
Sample Test Case
Input:
999999999999999999 2
Output:
1000000000000000001
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
[$a,$b]=preg_split('/\\s+/', $inputText, 2);
$a=ltrim($a,'0'); if($a==='') $a='0';
$b=ltrim($b,'0'); if($b==='') $b='0';
$i=strlen($a)-1; $j=strlen($b)-1; $carry=0; $out='';
while($i>=0 || $j>=0 || $carry){
$da=($i>=0)?(ord($a[$i])-48):0;
$db=($j>=0)?(ord($b[$j])-48):0;
$sum=$da+$db+$carry;
$out=chr(($sum%10)+48).$out;
$carry=intdiv($sum,10);
$i--; $j--;
}
echo $out;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!