Find Numbers with Even Number of Digits

Easy

Topics
ArrayMath

Given an array nums of integers, return how many of them contain an even number of digits.

Example 1

1203451226378964
even digit count
Shaded values have an even number of digits, so the answer is 2.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [12,345,2,6,7896]
Output: 2

Example 2

55509011482217713
even digit count
Input:  nums = [555,901,482,1771]
Output: 1

Constraints

  • 1 <= nums.length <= 500
  • 1 <= nums[i] <= 10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

Count how many values have an even digit count. The only decision is how to count digits.

Converting to a string and taking its length is the shortest expression of the idea and is what the solution does. The arithmetic alternative divides by 10 until the number is gone, which avoids allocating a string per element. With nums[i] <= 10^5 there is a third option: compare against range boundaries directly, since only 2-digit, 4-digit and the single 6-digit value 100000 qualify.

All three are O(1) per element and the difference is taste rather than complexity — worth saying so rather than implying one is cleverer.

Approach

  1. For each value, compute its digit count.
  2. Count the ones where that is even.

Dry Run

nums = [12, 345, 2, 6, 7896]

12    2 digits  even  ✓
345   3 digits  odd
2     1 digit   odd
6     1 digit   odd
7896  4 digits  even  ✓

answer 2

Complexity

  • Time — O(n): one pass; digit counting is bounded by the 6 digits the constraints allow, so constant per element.
  • Space — O(1): a counter. Note that str(x) does allocate a short-lived string per element, so a strict reading is O(1) amortised rather than zero allocation — the division loop allocates nothing at all.

Common Pitfalls

  • Using log10 to get the digit count. Floating point makes exact powers of ten land on the boundary, so 1000 can come out as 3 digits; if you use it, add 1 and floor carefully, or avoid it.
  • Looping while x > 0 without handling x == 0, which would report zero digits. The constraints start at 1 here, but the habit matters.
  • Counting characters of a negative number's string, where the minus sign inflates the count. Not possible under these constraints, which is why the abs is belt-and-braces.
  • Returning the matching values instead of how many there are.

Full Solution — all languages

class Solution:
    def findNumbers(self, nums):
        return sum(1 for x in nums if len(str(abs(x))) % 2 == 0)
SensAI
Beta
Tap the mic to stop voice mode