Find Numbers with Even Number of Digits
Problem
You are given an array nums of positive integers (up to 500 values, each between 1 and 10⁵). Return how many of them are written with an even number of digits. For example, 12 has two digits (even), while 345 has three (odd).
nums = [12, 345, 2, 6, 7896]2def find_numbers(nums):
count = 0
for x in nums:
digits = 0
while x > 0:
x //= 10
digits += 1
if digits % 2 == 0:
count += 1
return count
function findNumbers(nums) {
let count = 0;
for (let x of nums) {
let digits = 0;
while (x > 0) {
x = Math.floor(x / 10);
digits++;
}
if (digits % 2 === 0) count++;
}
return count;
}
int findNumbers(int[] nums) {
int count = 0;
for (int x : nums) {
int digits = 0;
while (x > 0) {
x /= 10;
digits++;
}
if (digits % 2 == 0) count++;
}
return count;
}
int findNumbers(vector<int>& nums) {
int count = 0;
for (int x : nums) {
int digits = 0;
while (x > 0) {
x /= 10;
digits++;
}
if (digits % 2 == 0) count++;
}
return count;
}
Explanation
The only thing that matters about each number is the parity of its digit length, not its value. So the whole problem reduces to: measure the digit length of every element, and count how many lengths are even.
To measure a digit length without converting to a string, repeatedly divide by 10 (integer division) and count how many divisions it takes to reach 0. Each division strips the last digit, so the number of strips equals the number of digits: 345 → 34 → 3 → 0 takes three steps, hence 3 digits.
With the default example [12, 345, 2, 6, 7896]: 12 needs 2 divisions (even, count becomes 1); 345 needs 3 (odd, skipped); 2 and 6 each need 1 (odd, skipped); 7896 needs 4 (even, count becomes 2). The answer is 2.
Two popular shortcuts give the same result. Converting each number to a string and checking len(str(x)) % 2 == 0 is the most direct. Or, since the constraint caps values at 10⁵, you can observe that the even-digit numbers in range are exactly those in [10, 99], [1000, 9999], and the single value 100000 — three interval checks and no loop at all.
The division loop runs once per digit, and every value has at most 6 digits under the constraint, so each element costs constant work. Over n elements that is O(n · d) time with d ≤ 6 — effectively linear — and only a couple of integer variables, so O(1) extra space.