algoadvance

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

Clarifying Questions:

  1. Input Range: What is the range of values in the input array nums?
    • The input values will be non-negative integers.
  2. Output: What do we return if there are no numbers with an even number of digits?
    • You would return 0 since no numbers have an even number of digits.
  3. Constraints:
    • The input array size (nums.length) will be in the range [1, 500].
    • Each integer in nums is in the range [1, 10^5].

Strategy:

To determine if a number has an even number of digits:

  1. Convert the integer to a string.
  2. Count the length of the string representation.
  3. Check if the length is even.

To count the total:

  1. Iterate through the list nums.
  2. For each number, check if it has an even number of digits.
  3. Maintain a counter to keep track of numbers with an even digit count.
  4. Return the counter value at the end.

Time Complexity:

Code:

def findNumbers(nums):
    even_digits_count = 0
    for num in nums:
        # Convert the number to string and check its length
        if len(str(num)) % 2 == 0:
            even_digits_count += 1
    return even_digits_count

# Example test case
nums = [12, 345, 2, 6, 7896]
print(findNumbers(nums))  # Output should be 2

This code will correctly count and return the number of integers in the nums array that have an even number of digits.

Try our interview co-pilot at AlgoAdvance.com