Big Integer Subtraction
PHP
Hard
4 views
Problem Description
Given a and b as big integers (a >= b), print a-b.
Input Format
One line: a b (a>=b).
Output Format
One integer string.
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; $borrow=0; $out='';
while($i>=0){
$da=ord($a[$i])-48-$borrow;
$db=($j>=0)?(ord($b[$j])-48):0;
if($da<$db){ $da+=10; $borrow=1; } else $borrow=0;
$out=chr(($da-$db)+48).$out;
$i--; $j--;
}
$out=ltrim($out,'0');
echo ($out===''?'0':$out);
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!