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.
1class Solution {
2 public int findNumbers(int[] nums) {
3 int count = 0;
4 for (int num : nums) {
5 if (String.valueOf(num).length() % 2 == 0) {
6 count++;
7 }
8 }
9 return count;
10 }
11
12 public static void main(String[] args) {
13 Solution sol = new Solution();
14 int[] nums = {12, 345, 2, 6, 7896};
15 System.out.println(sol.findNumbers(nums));
16 }
17}
This Java solution uses a loop to iterate through the given array, converts each number into a string using String.valueOf()
, checks if the length of that string is even, and if so, it counts that number.
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.