By Vivek - April 19, 2020
Find Numbers with Even Number of Digits in Python
This Python solution counts how many integers contain an even number of digits. The direct approach is to convert each number to a string, count its characters, and keep the values whose length is divisible by two.
Table of Contents
Problem:
Given an array nums of integers, return how many of them contain an even number of digits.
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. Constraints:
1 <= nums.length <= 500
1 <= nums[i] <= 10^5 Approach
For each number:
- Convert the number to a string.
- Count the number of characters.
- Check whether that count is even.
- Add it to the answer if
digits % 2 == 0.
This is easy to read and is fast enough for the given constraints.
Python Solution:
class Solution:
def findNumbers(self, nums):
count = 0
for num in nums:
if len(str(num)) % 2 == 0:
count += 1
return count
num_list = [12,345,2,6,7896]
print(Solution().findNumbers(num_list)) You can also write the same logic with a generator expression:
class Solution:
def findNumbers(self, nums):
return sum(1 for num in nums if len(str(num)) % 2 == 0) Complexity
- Time complexity:
O(n * d), wherenis the number of integers anddis the maximum digit count. - Space complexity:
O(d)for the temporary string representation of each number.
Frequently Asked Questions
Why does the solution convert numbers to strings?
String conversion makes digit counting straightforward and readable. With the input limits in this problem, it is efficient enough.
Can this be solved without converting to a string?
Yes. You can repeatedly divide each number by 10 to count digits, but the code is longer and does not improve the practical result for these constraints.
What makes a digit count even?
A number has an even digit count when the number of digits is divisible by 2. For example, 12 has two digits and 7896 has four digits.
Related Python guides
Related Posts
- K-Concatenation Maximum Sum in Python
- Maximum Subarray Sum with One Deletion in Python
- Reverse Parentheses Substrings in Python
- Count Servers that Communicate in Python
- Count Square Submatrices with All Ones in Python
- Find Winner on a Tic Tac Toe Game in Python
- Minimum Absolute Difference in Python
- Minimum Time Visiting All Points in Python
- Number of Burgers with No Waste of Ingredients in Python
- Search Suggestions System in Python