Find Numbers with Even Number of Digits
Easy
Topics
Given an array nums of integers, return how many of them contain an even number of digits.
Example 1
Input: nums = [12,345,2,6,7896] Output: 2
Example 2
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
- For each value, compute its digit count.
- 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 2Complexity
- 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
log10to get the digit count. Floating point makes exact powers of ten land on the boundary, so1000can come out as 3 digits; if you use it, add 1 and floor carefully, or avoid it. - Looping
while x > 0without handlingx == 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
absis 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)import java.util.*;
class Solution {
public int findNumbers(int[] nums) {
int c = 0;
for (int x : nums) if (Integer.toString(Math.abs(x)).length() % 2 == 0) c++;
return c;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int findNumbers(vector<int>& nums) {
int c = 0;
for (int x : nums) if (to_string(abs(x)).size() % 2 == 0) c++;
return c;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var findNumbers = function(nums) {
let c = 0;
for (const x of nums) if (String(Math.abs(x)).length % 2 === 0) c++;
return c;
};