We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find Numbers with Even Number of Digits

Number: 1421

Difficulty: Easy

Paid? No

Companies: Adobe, Quora


Problem Description

Given an array of integers, return the count of numbers that contain an even number of digits.


Key Insights

  • Process each number in the array independently.
  • Converting the number to a string and checking its length is an effective method to count digits.
  • Alternatively, use arithmetic operations (e.g., repeatedly dividing by 10) to count digits.
  • Only the parity (even or odd) of the count is important.

Space and Time Complexity

Time Complexity: O(n) where n is the number of integers in the array.
Space Complexity: O(1) as only a constant amount of extra space is used.


Solution

Iterate through the array and for each number, count the digits either by converting it to a string or via arithmetic division. Check if the digit count is even, and if so, increment a counter. Return the counter at the end.


Code Solutions

def findNumbers(nums):
    # Initialize counter for numbers with an even number of digits
    count = 0
    # Iterate through each number in the list
    for num in nums:
        # Convert the number to string to count digits and check for even length
        if len(str(num)) % 2 == 0:
            count += 1
    # Return the total count
    return count

# Example usage:
nums = [12, 345, 2, 6, 7896]
print(findNumbers(nums))  # Output: 2
← Back to All Questions