Sum of Digits at Even and Odd Places using Mathematical Operations
Another approach is to extract digits from the number using mathematical operations and then calculate the sums.
<?php
function evenOddDigitSum($num) {
$evenSum = 0;
$oddSum = 0;
while ($num > 0) {
$digit = $num % 10;
if ($digit % 2 == 0) {
$evenSum += $digit;
} else {
$oddSum += $digit;
}
$num = (int) ($num / 10);
}
return ["even" => $evenSum, "odd" => $oddSum];
}
// Driver code
$num = 123456;
$sums = evenOddDigitSum($num);
echo "Even Places Digit Sum: " . $sums["even"] . "\n";
echo "Odd Places Digit Sum: " . $sums["odd"];
?>
Output
Even Places Digit Sum: 12 Odd Places Digit Sum: 9
Sum of Digits at Even and Odd Places in PHP
Given a Number, the task is to sum the Digit of Even and Odd places using PHP. Calculating the sum of digits at even and odd places in a number is a common programming task. Here, we will cover all approaches with detailed explanations and code examples.
Table of Content
- Using a Loop
- Using Mathematical Operations