Find Numbers with Even Number of Digits

The problem asks to find how many integers in the array nums have an even number of digits.

Python solution:

1
2
3
4
5
6
7
8
9
class Solution:
    def findNumbers(self, nums: List[int]) -> int:
        count = 0

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

        return count

Explanation

  1. Initialization: We initialize a count variable as 0. This variable will hold the number of integers with an even number of digits.

  2. Iterating through the Numbers: We use a for loop to iterate through each number num in the given nums array.

  3. Checking Even Number of Digits: Inside the loop, we convert the number to a string using str(num), and then we check the length of this string using len(). If the length is even (len(str(num)) % 2 == 0), it means the number has an even number of digits, and we increment count by 1.

  4. Returning the Result: After the loop, we return the value of count, which represents the number of integers with an even number of digits in the given array.

title: Find Numbers with Even Number of Digits excerpt: Basic building block - reducing integer numbers in action. tags: integer-division reduce-value-by-integer-division counter

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] <= 10^5
How to compute the number of digits of a number ?
Divide the number by 10 again and again to get the number of digits.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# @param {Integer[]} nums
# @return {Integer}
def find_numbers(nums)
  output = 0
  count = 0
  
  nums.each do |n|
    while n != 0
      count += 1
      n = n/10
    end
  
    if count.even?
      output += 1
    end
    count = 0
  end
  
  output  
end

Integer division is used to reduce the integer by one number at a time. This is a basic building block that is useful in solving many problems.

Building Blocks

  • Integer Division
  • Reduce Value by Integer Division
  • Counter