LeetCode 题解工作台
统计位数为偶数的数字
给你一个整数数组 nums ,请你返回其中包含 偶数 个数位的数字的个数。 示例 1: 输入: nums = [12,345,2,6,7896] 输出: 2 解释: 12 是 2 位数字(位数为偶数) 345 是 3 位数字(位数为奇数) 2 是 1 位数字(位数为奇数) 6 是 1 位数字 位数为…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
我们遍历数组 中的每个元素,对于当前遍历到的元素 ,我们直接将其转换为字符串,然后判断其长度是否为偶数即可。若是则将答案加一。 遍历结束后,我们返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个整数数组 nums,请你返回其中包含 偶数 个数位的数字的个数。
示例 1:
输入:nums = [12,345,2,6,7896] 输出:2 解释: 12 是 2 位数字(位数为偶数) 345 是 3 位数字(位数为奇数) 2 是 1 位数字(位数为奇数) 6 是 1 位数字 位数为奇数) 7896 是 4 位数字(位数为偶数) 因此只有 12 和 7896 是位数为偶数的数字
示例 2:
输入:nums = [555,901,482,1771] 输出:1 解释: 只有 1771 是位数为偶数的数字。
提示:
1 <= nums.length <= 5001 <= nums[i] <= 105
解题思路
方法一:模拟
我们遍历数组 中的每个元素,对于当前遍历到的元素 ,我们直接将其转换为字符串,然后判断其长度是否为偶数即可。若是则将答案加一。
遍历结束后,我们返回答案即可。
时间复杂度 ,空间复杂度 。其中 是数组 的长度,而 是数组 中的元素的最大值。
class Solution:
def findNumbers(self, nums: List[int]) -> int:
return sum(len(str(x)) % 2 == 0 for x in nums)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Expect you to discuss both string-based and math-based digit counting.
- question_mark
They may ask how to optimize for space without creating new arrays.
- question_mark
Be ready to justify O(N) time as sufficient for array sizes up to 500.
常见陷阱
外企场景- error
Forgetting to handle single-digit numbers correctly when counting digits.
- error
Using string conversion unnecessarily when division or log10 is faster and cleaner.
- error
Miscounting numbers like 10 or 100 due to off-by-one errors in digit calculation.
进阶变体
外企场景- arrow_right_alt
Return the actual numbers with even digits instead of just the count.
- arrow_right_alt
Count numbers with an odd number of digits instead of even digits.
- arrow_right_alt
Apply the same logic to a list of negative numbers and zero.