Problem
Given an array of positive integers, count how many of them have an even number of digits. A single-digit number has 1 digit (odd), a two-digit number like 12 has 2 digits (even), and so on.
- Input:
nums = [12, 345, 2, 6, 7896] - Output:
2 - Explanation: 12 has 2 digits and 7896 has 4 digits โ both even; the other three have odd digit counts.
Intuition
The simplest way to count digits is to convert the number to its string representation and measure the length. A number has an even number of digits when that length is divisible by 2. Since there is no smarter data structure or algorithm to exploit here, one clean linear pass is all it takes.
Solution โ String Length Check
For each number, convert it to a string, check whether the length is even, and accumulate the count.
- Iterate over every number in the array.
- Convert the number to its string representation.
- Check whether the string length is divisible by 2.
- Increment the count if so.
- Return the final count.
1def find_numbers(nums: list[int]) -> int:
2 return sum(1 for num in nums if len(str(num)) % 2 == 0)Time: O(n ยท d), where d is the number of digits in the largest element (at most 6 for the given constraint of nums[i] โค 10โต), so effectively O(n).
Space: O(d) for the temporary string created per element โ effectively O(1).
Complexity Summary
| Approach | Time | Space | When to use |
|---|---|---|---|
| String Length Check | O(n) | O(1) | Always โ the constraint bounds digits to โค 6, making this linear in practice |
Common Mistakes
- Inverting the condition โ checking
len % 2 != 0returns the count of numbers with odd digit counts instead of even. - Wrapping in
abs()unnecessarily โ the problem guarantees positive integers, soabs()adds noise without benefit. - Math division approach off-by-one โ counting how many times you can divide by 10 before reaching 0 gives digits โ 1, not digits (e.g.
12 // 10 = 1, one more division gives 0, so two divisions for a 2-digit number โ the loop must count iterations, not just the final value). - Assuming
str(0)has 0 digits โstr(0)is"0"with length 1, which matters if you ever adapt this for arrays containing zero. - Range-checking only for the given constraints โ a hardcoded check like
10 <= num <= 99 or 1000 <= num <= 9999works for nums[i] โค 10โต but silently breaks for larger inputs; the string approach generalizes automatically.
Related Problems
reverse-integerโ extracts individual digits via repeated division, the math-based alternative to string conversionpalindrome-numberโ determines a property of a number's digit sequence without converting to stringplus-oneโ manipulates the digit representation of an integer stored as an arraycount-primesโ same pattern of iterating an array and counting elements that satisfy a numeric propertysqrtxโ integer math on a number's magnitude, similar to reasoning about the scale of a value