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.
1def findNumbers(nums):
2 count = 0
3 for num in nums:
4 if len(str(num)) % 2 == 0:
5 count += 1
6 return count
7
8nums = [12, 345, 2, 6, 7896]
9print(findNumbers(nums))
This Python function iterates over the list, converts each number to a string, and increments the count if the length of the string (number of digits) is even.
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
This Java solution involves computing the number of digits in a number using the logarithmic property. The Math.log10()
function is used, and the count of even-digit numbers is updated accordingly.