Find Numbers with Even Number of Digits — Problem & Solution
Find Numbers with Even Number of Digits solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Find Numbers with Even Number of Digits is an easy coding problem on arrays and math, asked in Amazon, TCS and Capgemini interviews.
- Difficulty: Easy
- Topics: Arrays, Math
- Asked at: Amazon, TCS, Capgemini
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
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 has 2 digits and 7896 has 4; the rest have an odd count.
Example 2
Input: nums = [555,901,482,1771]
Output: 1
Explanation: Only 1771 has an even number of digits.
Example 3
Input: nums = [1,2,3]
Output: 0
Constraints
1 <= nums.length <= 501 <= nums[i] <= 100000
Hints for Find Numbers with Even Number of Digits
Hint 1
Digit count is just the length of the decimal representation.
Hint 2
Or count divisions by 10 until the value reaches zero, if you would rather avoid strings.
How to solve Find Numbers with Even Number of Digits
The digit count is the length of the decimal representation; count the elements whose length is even.
Approach
- For each number, take the length of its decimal string (or count divisions by 10).
- Increment when that length is even.
- Return the count.
Why it works
The problem is a straightforward filter; the only decision is how to count digits, and both the string length and the repeated-division loop give the same answer.
Complexity
- Time —
O(n · digits) - Space —
O(1)
Pitfalls
- Values are positive per the constraints, so no sign character sneaks into the length.
- A range check (
10 <= x < 100 or 1000 <= x < 10000 …) also works but is easy to get wrong at the boundaries.
Reference solution
Python
def findNumbers(nums):
return sum(1 for x in nums if len(str(x)) % 2 == 0)Java
public static int findNumbers(int[] nums) {
int count = 0;
for (int v : nums) {
int digits = 0, x = v;
while (x > 0) {
digits++;
x /= 10;
}
if (digits % 2 == 0) count++;
}
return count;
}C++
int findNumbers(vector<int>& nums) {
int count = 0;
for (int v : nums) {
int digits = 0, x = v;
while (x > 0) {
digits++;
x /= 10;
}
if (digits % 2 == 0) count++;
}
return count;
}JavaScript
var findNumbers = function(nums) {
let count = 0;
for (let i = 0; i < nums.length; i++) {
if (String(nums[i]).length % 2 === 0) count++;
}
return count;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays