Move all zeros to the end
EASY
Given an input string with numbers separated by a single space.
Move all zeros to the end. The solution should maintain the relative order of items in the line.
Solution
<?php
$line = trim(fgets(STDIN));
$nums = explode(' ', $line);
$zerosCount = 0;
foreach ($nums as $num) {
if ($num == 0) {
$zerosCount++;
} else {
echo $num . ' ';
}
}
echo str_repeat('0 ', $zerosCount);
Tests
Test #1 |
Loading...
|
Test #2 |
Loading...
|
Test #3 |
Loading...
|
Test #4 |
Loading...
|