LeetCode 题解工作台

统计位数为偶数的数字

给你一个整数数组 nums ,请你返回其中包含 偶数 个数位的数字的个数。 示例 1: 输入: nums = [12,345,2,6,7896] 输出: 2 解释: 12 是 2 位数字(位数为偶数) 345 是 3 位数字(位数为奇数) 2 是 1 位数字(位数为奇数) 6 是 1 位数字 位数为…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

我们遍历数组 中的每个元素,对于当前遍历到的元素 ,我们直接将其转换为字符串,然后判断其长度是否为偶数即可。若是则将答案加一。 遍历结束后,我们返回答案即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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 <= 500
  • 1 <= nums[i] <= 105
lightbulb

解题思路

方法一:模拟

我们遍历数组 nums\textit{nums} 中的每个元素,对于当前遍历到的元素 xx,我们直接将其转换为字符串,然后判断其长度是否为偶数即可。若是则将答案加一。

遍历结束后,我们返回答案即可。

时间复杂度 O(n×logM)O(n \times \log M),空间复杂度 O(logM)O(\log M)。其中 nn 是数组 nums\textit{nums} 的长度,而 MM 是数组 nums\textit{nums} 中的元素的最大值。

1
2
3
4
class Solution:
    def findNumbers(self, nums: List[int]) -> int:
        return sum(len(str(x)) % 2 == 0 for x in nums)
speed

复杂度分析

指标
时间O(N)
空间O(1)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

统计位数为偶数的数字题解:数组·数学 | LeetCode #1295 简单