3754. Concatenate Non-Zero Digits and Multiply by Sum I #3322
|
Topics: You are given an integer Form a new integer Let Return an integer representing the value of Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Example 6:
Example 7:
Constraints:
Hint:
|
Replies: 1 comment 2 replies
|
We implement a straightforward solution that processes the input integer Approach
Let's implement this solution in PHP: 3754. Concatenate Non-Zero Digits and Multiply by Sum I <?php
/**
* @param Integer $n
* @return Integer
*/
function sumAndMultiply(int $n): int
{
$digits = str_split((string) $n);
$nonZeroDigits = array_filter($digits, fn($d) => $d !== '0');
if (empty($nonZeroDigits)) {
return 0;
}
$x = (int) implode('', $nonZeroDigits);
$sum = array_sum($nonZeroDigits);
return $x * $sum;
}
// Test cases
echo sumAndMultiply(10203004) . "\n"; // Output: 12340
echo sumAndMultiply(1000) . "\n"; // Output: 1
echo sumAndMultiply(0) . "\n"; // Output: 0
echo sumAndMultiply(5) . "\n"; // Output: 25
echo sumAndMultiply(123456789) . "\n"; // Output: 5555555505
echo sumAndMultiply(101010) . "\n"; // Output: 333
echo sumAndMultiply(1000000000) . "\n"; // Output: 1
?>Explanation:
Complexity Analysis
|
We implement a straightforward solution that processes the input integer
nby extracting all non-zero digits, constructing a new number from them, calculating their sum, and returning their product. Our approach handles the edge case where no non-zero digits exist by returning 0.Approach
nto a string and split it into an array of individual digit characters