By Vivek - April 19, 2020

Find Numbers with Even Number of Digits in Python

This Python solution counts how many integers contain an even number of digits. The direct approach is to convert each number to a string, count its characters, and keep the values whose length is divisible by two.

Table of Contents

  1. Problem
  2. Approach
  3. Python solution
  4. Complexity
  5. Frequently asked questions
  6. Related Python guides

Problem:

Given an array nums of integers, return how many of them contain an even number of digits.

Input: nums = [12,345,2,6,7896]

Output: 2

Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.

Constraints:

1 <= nums.length <= 500

1 <= nums[i] <= 10^5

Approach

For each number:

  1. Convert the number to a string.
  2. Count the number of characters.
  3. Check whether that count is even.
  4. Add it to the answer if digits % 2 == 0.

This is easy to read and is fast enough for the given constraints.

Python Solution:

class Solution:
  def findNumbers(self, nums):
    count = 0

    for num in nums:
      if len(str(num)) % 2 == 0:
        count += 1

    return count


num_list = [12,345,2,6,7896]
print(Solution().findNumbers(num_list))

You can also write the same logic with a generator expression:

class Solution:
  def findNumbers(self, nums):
    return sum(1 for num in nums if len(str(num)) % 2 == 0)

Complexity

  • Time complexity: O(n * d), where n is the number of integers and d is the maximum digit count.
  • Space complexity: O(d) for the temporary string representation of each number.

Frequently Asked Questions

Why does the solution convert numbers to strings?
String conversion makes digit counting straightforward and readable. With the input limits in this problem, it is efficient enough.
Can this be solved without converting to a string?
Yes. You can repeatedly divide each number by 10 to count digits, but the code is longer and does not improve the practical result for these constraints.
What makes a digit count even?
A number has an even digit count when the number of digits is divisible by 2. For example, 12 has two digits and 7896 has four digits.

Related Python guides