Sum Only Numeric Tokens
PHP
Medium
3 views
Problem Description
Given a line with mixed tokens, add only the numeric ones and print the sum. Print as integer if it is whole.
Input Format
One line with tokens.
Output Format
One number sum.
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$parts=preg_split('/\\s+/', $inputText);
$sum=0.0;
foreach($parts as $t){
if($t==='') continue;
if(is_numeric($t)) $sum+=floatval($t);
}
if(abs($sum-round($sum))<1e-9) echo strval(intval(round($sum)));
else{
$s=rtrim(rtrim(number_format($sum,10,'.',''),'0'),'.');
echo $s;
}
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!