MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Sum Only Numeric Tokens with Explanation

PHP Medium PHP Data Types 25 views
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around sum, token, only. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

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.

Constraints

Total text

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?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; } ?>

Output Example

Input:
10 cat 2.5 dog -3
Output:
9.5

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next