Problem
Given an array nums
of integers, return how many of them contain an even number of digits.
Examples
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.
Solution
Method 1 - Convert numbers to string
- Convert each number to its string representation to count the number of digits.
- Check if the number of digits is even.
- Count how many numbers satisfy the condition.
Code
Java
public class Solution {
public int countEvenDigitNumbers(int[] nums) {
int count = 0;
for (int num : nums) {
if (numberOfDigits(num) % 2 == 0) {
count += 1;
}
}
return count;
}
private int numberOfDigits(int num) {
return (int) Math.log10(num) + 1;
}
}
Python
def find_floor(arr, x):
start, end = 0, len(arr) - 1
floor = -1
while start <= end:
mid = (start + end) // 2
if arr[mid] == x:
return arr[mid]
elif arr[mid] < x:
floor = arr[mid]
start = mid + 1
else:
end = mid - 1
Complexity
- Time:
O(n)
, wheren
is the length of the array. Each number is processed individually. - Space:
O(1)
, as we are not using additional space proportional to the input size, aside from the space required for the count and temporary variables.