统计对称整数的数目
问题分析
根据题目描述,我们需要编写一个 Python 程序来计算在给定范围 [low, high] 内的对称整数的数量。对称整数的定义是:一个由 2 * n 位数字组成的整数 x,如果其前 n 位数字之和与后 n 位数字之和相等,则认为这个数字是对称整数。
思考
暴力枚举
遍历范围:从 low 到 high 遍历每个整数。
检查是否为对称整数:
将整数转换为字符串,方便分割和处理。
检查整数的位数是否为偶数。
如果是偶数位,将字符串分成前后两部分,分别计算两部分数字之和。
如果两部分的数字之和相等,则该整数是对称整数。
统计对称整数的数量:在遍历过程中,累计符合条件的对称整数数量。
代码
class Solution:
def countSymmetricIntegers(self, low: int, high: int) -> int:
def is_symmetric(num_str: str) -> bool:
# 检查数字是否为偶数位
if len(num_str) % 2 != 0:
return False
# 分割成前后两部分
n = len(num_str) // 2
first_half = num_str[:n]
second_half = num_str[n:]
# 计算两部分数字之和
sum_first_half = sum(int(digit) for digit in first_half)
sum_second_half = sum(int(digit) for digit in second_half)
# 判断两部分数字之和是否相等
return sum_first_half == sum_second_half
# 统计对称整数的数量
count = 0
for num in range(low, high + 1):
if is_symmetric(str(num)):
count += 1
return count
复杂度分析
时间复杂度:O(m*n)
空间复杂度:O(1)
学习
is_symmetric 函数:
输入是一个字符串形式的数字。
首先检查数字的长度是否为偶数,如果不是则直接返回 False。
将字符串分成前后两部分,分别计算两部分数字之和。
如果两部分的数字之和相等,则返回 True,否则返回 False。
主函数 count_symmetric_integers:
遍历范围 [low, high] 中的每个整数。
将整数转换为字符串,调用 is_symmetric 函数判断是否为对称整数。
如果是对称整数,则计数器加一。
最终返回对称整数的总数。
暴力枚举时间复杂度高,容易超时
上下界数位 DP
代码
class Solution:
def countSymmetricIntegers(self, low: int, high: int) -> int:
high = list(map(int, str(high))) # 避免在 dfs 中频繁调用 int()
n = len(high)
low = list(map(int, str(low).zfill(n))) # 补前导零,和 high 对齐
@cache
def dfs(i: int, start: int, diff: int, limit_low: bool, limit_high: bool) -> int:
if i == n:
return 1 if diff == 0 else 0
lo = low[i] if limit_low else 0
hi = high[i] if limit_high else 9
# 如果前面没有填数字,且剩余数位个数是奇数,那么当前数位不能填数字
if start < 0 and (n - i) % 2:
# 如果必须填数字(lo > 0),不合法,返回 0
return 0 if lo else dfs(i + 1, start, diff, True, False)
res = 0
is_left = start < 0 or i < (start + n) // 2
for d in range(lo, hi + 1):
res += dfs(i + 1,
i if start < 0 and d else start, # 记录第一个填数字的位置
diff + (d if is_left else -d), # 左半 + 右半 -
limit_low and d == lo,
limit_high and d == hi)
return res
return dfs(0, -1, 0, True, True)
来源:
作者:灵茶山艾府
链接:https://leetcode.cn/problems/count-symmetric-integers/solutions/2424088/mei-ju-by-endlesscheng-oo2d/