Home

Even Number of Digits

Two tower buildings side by side Photo by JOHN TOWNER

This post is part of the Algorithms Problem Solving series.

Problem description

This is the Find Numbers with Even Number of Digits problem. The description looks like this:

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

Examples

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

Input: nums = [555,901,482,1771]
Output: 1

Solution

The solution idea is to iterate through the numbers list and for each number, verify how many digits it has and if it has an even digits number, increment the counter.

Using Python3, we can transforma the number into a string and get the length of it. If it is divisble by 2, it is an even number of digits.

def find_numbers(nums):
    counter = 0

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

    return counter

Resources

Have fun, keep learning, and always keep coding!

My Twitter and Github

Patreon Become a Patron Coffee icon Buy me a coffee