2843. Count Symmetric Integers #1546
-
Topics: You are given two positive integers An integer Return the number of symmetric integers in the range Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count the number of symmetric integers within a given range [low, high]. A symmetric integer is defined as a number with an even number of digits where the sum of the first half of the digits is equal to the sum of the second half of the digits. Approach
Let's implement this solution in PHP: 2843. Count Symmetric Integers <?php
/**
* @param Integer $low
* @param Integer $high
* @return Integer
*/
function countSymmetricIntegers($low, $high) {
$count = 0;
for ($num = $low; $num <= $high; $num++) {
$s = (string)$num;
$len = strlen($s);
if ($len % 2 != 0) {
continue;
}
$half = $len / 2;
$sum1 = 0;
for ($i = 0; $i < $half; $i++) {
$sum1 += intval($s[$i]);
}
$sum2 = 0;
for ($i = $half; $i < $len; $i++) {
$sum2 += intval($s[$i]);
}
if ($sum1 == $sum2) {
$count++;
}
}
return $count;
}
// Example usage:
echo countSymmetricIntegers(1, 100); // Output: 9
echo "\n";
echo countSymmetricIntegers(1200, 1230); // Output: 4
?> Explanation:
This approach efficiently checks each number in the range and ensures we only consider valid symmetric integers, providing the correct count with a time complexity of O(N * M), where N is the range size and M is the average number of digits, which is manageable given the problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to count the number of symmetric integers within a given range [low, high]. A symmetric integer is defined as a number with an even number of digits where the sum of the first half of the digits is equal to the sum of the second half of the digits.
Approach
low
tohigh
inclusive.