easy

Find Numbers with Even Number of Digits

Count how many numbers in an array have an even digit count.

1. Define the problem

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

Inputnums = [12, 345, 2, 6, 7896]
Output2

Explanation 12 has 2 digits and 7896 has 4 digits, both even — the other numbers have an odd digit count.

2. Know the words first

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).
3. Visualize the solution

Count the digits of each number and check for evenness

Count the digits of each number and check for evenness
Statusinit

value=12 has 2 digits, even. count=1.

What happens in this step

value = nums[0] = 12
digit count = 2 (even)

count becomes 1.
Step 1 of 4

Steps to visualize

  1. For each number in the array, count how many digits it has.
  2. If that digit count is even, increment a running count.
  3. Continue through the whole array and return the final count.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Count the digits of each number and check for evenness
Statusinit

value=12 has 2 digits, even. count=1.

What happens in this step

value = nums[0] = 12
digit count = 2 (even)

count becomes 1.
Step 1 of 4
5. Solution

Solution

solution.tsTypeScript
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)
6. Test cases

Test cases

InputExpectedCovers
nums = [12, 345, 2, 6, 7896]2example from the docstring
nums = [1, 22, 333, 4]1only one number has an even digit count
nums = [5]0smallest valid input, a single one-digit number
nums = [10, 20, 30]3every number has two digits
nums = [100000]1largest allowed number, six digits
nums = [9, 99, 999, 9999]2a range of digit lengths from 1 to 4