Find Numbers with Even Number of Digits
Given an array nums of integers, return how many of them contain an even number of digits . For each number, convert it to a string and check the length of that string, or repeatedly divide by 10 to count digits without ever building a string.
Constraints
- 1 ≤ nums.length ≤ 500
- 1 ≤ numsi ≤ 105
Example
nums = [12, 345, 2, 6, 7896]2Explanation 12 has 2 digits and 7896 has 4 digits, both even — the other numbers have an odd digit count.
In plain terms
- Even number of digits
- The count of digits in the number is divisible by two, like 1234 (4 digits) or 99 (2 digits).
Count the digits of each number and check for evenness
value=12 has 2 digits, even. count=1.
What happens in this step
value = nums[0] = 12 digit count = 2 (even) count becomes 1.
Steps to visualize
- For each number in the array, count how many digits it has.
- If that digit count is even, increment a running count.
- Continue through the whole array and return the final count.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
value=12 has 2 digits, even. count=1.
What happens in this step
value = nums[0] = 12 digit count = 2 (even) count becomes 1.
Solution
function findNumbers(nums) {
let count = 0;
for (const value of nums) {
const digitCount = String(value).length;
if (digitCount % 2 === 0) {
count++;
}
}
return count;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [12, 345, 2, 6, 7896] | 2 | example from the docstring |
nums = [1, 22, 333, 4] | 1 | only one number has an even digit count |
nums = [5] | 0 | smallest valid input, a single one-digit number |
nums = [10, 20, 30] | 3 | every number has two digits |
nums = [100000] | 1 | largest allowed number, six digits |
nums = [9, 99, 999, 9999] | 2 | a range of digit lengths from 1 to 4 |