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
In C, we use the log10()
function to calculate the number of digits. The logarithm of base 10 of any number n will give d - 1 where d is the number of digits in a number. By checking if (int)log10(nums[i]) + 1
is even, we determine if the number has an even digit count.