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.
1using System;
2
3class Program {
4 static int FindNumbers(int[] nums) {
5 int count = 0;
6 foreach (var num in nums) {
7 if (num.ToString().Length % 2 == 0) {
8 count++;
9 }
10 }
11 return count;
12 }
13
14 static void Main() {
15 int[] nums = {12, 345, 2, 6, 7896};
16 Console.WriteLine(FindNumbers(nums));
17 }
18}
This C# program declares a method that checks the length of each integer in terms of its string representation and increments the count if it has an even number of digits.
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
The JavaScript solution uses Math.log10()
to calculate the digit count and checks their evenness to update the counter of such numbers.