[Arrays] Find Numbers with Even Number of Digits

Date:     Updated:

Categories:

Tags:

📋 This is my note-taking from what I learned in LeetCode!


Problem

Problem Link

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

Example 1:

  • 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.

Example 2:

  • Input: nums = [555,901,482,1771]
  • Output: 1
  • Explanation:
    • Only 1771 contains an even number of digits.

Constraints:

1 <= nums.length <= 500 1 <= nums[i] <= 105

Hint #1:

How to compute the number of digits of a number?

Hint #2:

Divide the number by 10 again and again to get the number of digits.


Solution

Approach 1

Algorithm:

  1. Define a function named find_even_digits that takes an array of integers as an argument.
  2. Initialize a variable count to zero, which will keep track of the number of integers that have an even number of digits.
  3. Loop through each integer in the array.
  4. Convert the integer to a string and calculate the length of the string to determine the number of digits in the integer.
  5. If the number of digits is even, increment the count variable.
  6. Return the count variable as the result of the function.
def find_numbers(nums: list[int]) -> int:
    count = 0
    for num in nums:
        digits = 0
        while num > 0:
            digits += 1
            num //= 10
        if digits % 2 == 0:
            count += 1
    return count

nums = [12, 345, 6789, 12345]

print(find_numbers(nums))


Approach 2

Algorithm:

  1. Initialize a variable result to 0.
  2. For each integer num in the input array nums, do the following:
    a. Calculate the number of digits in num using int(math.log10(num)) + 1.
    b. If the number of digits is even, increment result.
  3. Return result.
import math

def find_numbers(nums: list[int]) -> int:
    result = 0

    for num in nums:
        # Compute the number of digits of the current number
        num_digits = int(math.log10(num)) + 1

        # Check if the number of digits is even
        if num_digits % 2 == 0:
            result += 1

    return result

nums = [12, 345, 6789, 12345]

print(find_numbers(nums))




Back to Top

See other articles in Category Arrays

Leave a comment