Given an array of integers nums
, your task is to count how many numbers in the array contain an even number of digits.
For example, given nums = [12, 345, 2, 6, 7896]
, the numbers with an even number of digits are 12
and 7896
(since they have 2 and 4 digits, respectively).
Constraints:
1 <= nums.length <= 500
1 <= nums[i] <= 10^5
nums
that have an even number of digits.
The problem asks us to count numbers in an array based on the number of digits they have. The most direct way is to check each number, determine how many digits it contains, and count it if that number is even.
At first, you might think to convert each number to a string and check the length, since counting characters in a string is straightforward. Alternatively, you could use math: repeatedly divide the number by 10 until it becomes 0, counting how many times this happens.
Both approaches are valid. Since the constraints are small (arrays up to 500 elements), either approach will work efficiently. However, converting to a string is typically simpler and more readable.
We want to avoid unnecessary complexity, so we look for the most direct and efficient solution that fits the problem's constraints.
Let's break down the solution step by step:
nums
:
Let's use the sample input nums = [12, 345, 2, 6, 7896]
:
Brute-force Approach:
n
numbers, the total time is O(n).
The problem reduces to checking, for each number in the array, whether its digit count is even. We can efficiently do this by converting each number to a string and checking the length, or by counting digits mathematically. The solution is straightforward and efficient due to the small input size, and it highlights the value of simple, readable code for common array-processing tasks.
class Solution:
def findNumbers(self, nums):
count = 0
for num in nums:
if len(str(num)) % 2 == 0:
count += 1
return count
class Solution {
public:
int findNumbers(vector<int>& nums) {
int count = 0;
for (int num : nums) {
int digits = 0, n = num;
while (n > 0) {
digits++;
n /= 10;
}
if (digits % 2 == 0) {
count++;
}
}
return count;
}
};
class Solution {
public int findNumbers(int[] nums) {
int count = 0;
for (int num : nums) {
int digits = 0, n = num;
while (n > 0) {
digits++;
n /= 10;
}
if (digits % 2 == 0) {
count++;
}
}
return count;
}
}
var findNumbers = function(nums) {
let count = 0;
for (let num of nums) {
if (num.toString().length % 2 === 0) {
count++;
}
}
return count;
};