Sponsored
Sponsored
This approach involves converting each number into a string to easily count the number of digits.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(1), as we're using a fixed amount of extra space.
1function findNumbers(nums) {
2 let count = 0;
3 for (let num of nums) {
4 if (num.toString().length % 2 === 0) {
5 count++;
6 }
7 }
8 return count;
9}
10
11const nums = [12, 345, 2, 6, 7896];
12console.log(findNumbers(nums));
This JavaScript solution iterates over the array of numbers, converts each number to a string, and checks whether the length of the string is even. It increments the count for numbers that have even digit lengths.
The logarithmic approach calculates the number of digits by using logarithms; specifically, the base-10 logarithm of a number is taken, and the result is incremented by 1 to get the total number of digits.
Time Complexity: O(n), the array is processed once.
Space Complexity: O(1), constant space utilized.
1
class Program {
static int FindNumbers(int[] nums) {
int count = 0;
foreach (var num in nums) {
if ((int)Math.Floor(Math.Log10(num) + 1) % 2 == 0) {
count++;
}
}
return count;
}
static void Main() {
int[] nums = {12, 345, 2, 6, 7896};
Console.WriteLine(FindNumbers(nums));
}
}
In C# the logarithmic approach uses Math.Log10()
and Math.Floor()
to determine the number of digits directly, checking for even count.