Problem
You are given two positive integers low
and high
.
An integer x
consisting of 2 * n
digits is symmetric if the sum of the first n
digits of x
is equal to the sum of the last n
digits of x
. Numbers with an odd number of digits are never symmetric.
Return the number of symmetric integers in the range [low, high]
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= low <= high <= 104
Solution
Method 1 - Iteration
- Symmetric Checks:
- A number is symmetric if it has an even number of digits (
2 * n
digits). - Split the digits into two halves, sum them, and check if they are equal.
- Numbers with odd digits are skipped.
- A number is symmetric if it has an even number of digits (
- Steps in the Solution:
- Iterate through all integers in the range
[low, high]
. - Convert each integer to a string, check if it has an even number of digits.
- For numbers with even digits, compute the sum of the first
n
digits and the lastn
digits to determine symmetry. - Count the symmetric numbers.
- Iterate through all integers in the range
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O((high-low+1) * d)
- We iterate through all numbers in
[low, high]
. - For each number with
d
digits, we compute sums, which takesO(d)
.
- We iterate through all numbers in
- 🧺 Space complexity:
O(d)
. In python, due to string conversion and slicing. In java, due to string storage during the iteration.