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] <= 105
This problem asks to count the numbers in an array that have an even number of digits. The most straightforward approach is to iterate through the array and check the number of digits in each number.
x
) in the input array nums
.x
to a string using the built-in string conversion functions (e.g., str()
in Python, String.valueOf()
in Java, to_string()
in C++).len()
function (or equivalent) and check if this length is even using the modulo operator (%
).ans
or similar).Time Complexity: O(n * log10(M)), where n is the length of the input array nums
, and M is the maximum value in the array. The logarithmic factor comes from the fact that the number of digits in a number x
is proportional to log10(x). Converting an integer to a string has a time complexity related to the number of digits. In practice, this is usually very fast, making the overall time complexity dominated by the linear traversal of the array.
Space Complexity: O(log10(M)). This is because the space used by the string representation of a number is proportional to the number of digits (log10(M)). In most implementations, this space is relatively small compared to the input array size.
The solutions below demonstrate the approach in several popular programming languages. The core logic remains consistent across all implementations:
Python:
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
Java:
class Solution {
public int findNumbers(int[] nums) {
int count = 0;
for (int num : nums) {
if (String.valueOf(num).length() % 2 == 0) {
count++;
}
}
return count;
}
}
C++:
class Solution {
public:
int findNumbers(vector<int>& nums) {
int count = 0;
for (int num : nums) {
if (to_string(num).length() % 2 == 0) {
count++;
}
}
return count;
}
};
JavaScript:
var findNumbers = function(nums) {
let count = 0;
for (let num of nums) {
if (String(num).length % 2 === 0) {
count++;
}
}
return count;
};
Go:
func findNumbers(nums []int) int {
count := 0
for _, num := range nums {
if len(strconv.Itoa(num)) % 2 == 0 {
count++
}
}
return count
}
These solutions all follow the same algorithm and have the same time and space complexity. The choice of language depends on personal preference and the context of the problem's usage.