Given an array nums of integers, return how many of them contain an even number of digits.
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.
Constraints:
1 <= nums.length <= 5001 <= nums[i] <= 105This approach involves converting each number into a string to easily count the number of digits.
This C code goes through each number in the array, converts the number to a string, and checks if the length of that string is even. If it is, it increments the count of numbers with an even number of digits.
C++
Java
Python
C#
JavaScript
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.
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.
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.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), the array is processed once.
Space Complexity: O(1), constant space utilized.
| Approach | Complexity |
|---|---|
| Convert to String Approach | Time Complexity: O(n), where n is the number of elements in the array. |
| Logarithmic Approach | Time Complexity: O(n), the array is processed once. |
LeetCode 168 Problem 1 - Find Numbers with Even Number of Digits • code_report • 7,639 views views
Watch 9 more video solutions →Practice Find Numbers with Even Number of Digits with our built-in code editor and test cases.
Practice on FleetCode