LeetCode 题解工作台
统计各位数字之和为偶数的整数个数
给你一个正整数 num ,请你统计并返回 小于或等于 num 且各位数字之和为 偶数 的正整数的数目。 正整数的 各位数字之和 是其所有位上的对应数字相加的结果。 示例 1: 输入: num = 4 输出: 2 解释: 只有 2 和 4 满足小于等于 4 且各位数字之和为偶数。 示例 2: 输入: …
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·结合·模拟
答案摘要
一种最简单直接的方法是枚举 的所有整数 ,判断 各位数字之和是否为偶数,是则答案加一。 时间复杂度 $O(n \times \log n)$,空间复杂度 。其中 为 的值。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·模拟 题型思路
题目描述
给你一个正整数 num ,请你统计并返回 小于或等于 num 且各位数字之和为 偶数 的正整数的数目。
正整数的 各位数字之和 是其所有位上的对应数字相加的结果。
示例 1:
输入:num = 4 输出:2 解释: 只有 2 和 4 满足小于等于 4 且各位数字之和为偶数。
示例 2:
输入:num = 30 输出:14 解释: 只有 14 个整数满足小于等于 30 且各位数字之和为偶数,分别是: 2、4、6、8、11、13、15、17、19、20、22、24、26 和 28 。
提示:
1 <= num <= 1000
解题思路
方法一:枚举
一种最简单直接的方法是枚举 的所有整数 ,判断 各位数字之和是否为偶数,是则答案加一。
时间复杂度 ,空间复杂度 。其中 为 的值。
class Solution:
def countEven(self, num: int) -> int:
ans = 0
for x in range(1, num + 1):
s = 0
while x:
s += x % 10
x //= 10
ans += s % 2 == 0
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(num * d) where d is the number of digits, due to computing digit sums for each number. Space complexity is O(1) since only a counter and temporary variables are used. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate immediately recognizes the Math plus Simulation pattern.
- question_mark
Listen for an explanation of digit sum computation without extra arrays.
- question_mark
Watch if they avoid overcomplicating the iteration with unnecessary data structures.
常见陷阱
外企场景- error
Forgetting that single-digit numbers still count if their digit sum is even.
- error
Using string conversion without considering efficiency in larger num ranges.
- error
Returning an incorrect count by checking for odd sums instead of even sums.
进阶变体
外企场景- arrow_right_alt
Count numbers with odd digit sums instead of even.
- arrow_right_alt
Return a list of all numbers with even digit sums rather than just the count.
- arrow_right_alt
Handle larger num values efficiently using modulo arithmetic patterns.