Description
Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
1Input: nums = [12,345,2,6,7896]
2Output: 2
3Explanation:
412 contains 2 digits (even number of digits).
5345 contains 3 digits (odd number of digits).
62 contains 1 digit (odd number of digits).
76 contains 1 digit (odd number of digits).
87896 contains 4 digits (even number of digits).
9Therefore only 12 and 7896 contain an even number of digits.
Example 2:
1Input: nums = [555,901,482,1771]
2Output: 1
3Explanation:
4Only 1771 contains an even number of digits.
Constraints:
1 <= nums.length <= 5001 <= nums[i] <= 10^5
Solution
The simplest idea will be to convert each of the numbers into string and then for each string, check if their length is even or odd.
1class Solution {
2 public int findNumbers(int[] nums) {
3 int evenDigits = 0;
4 for (int num: nums) {
5 if (String.valueOf(num).length() % 2 == 0) {
6 evenDigits++;
7 }
8 }
9 return evenDigits;
10 }
11}
Time Complexity: O(n log m) where n = length of nums and m = maximum integer in nums.
Space Complexity: O(log m)
Another alternative to this approach is to extract the digits from each number in nums array and check if it contains even number of digits. In this case, we will not be creating any string, we are only creating fixed number of variables regardless of the size of nums. So, this gives us improvement in space complexity to O(1).
To find if the number has even number of digits, we can create a helper method.
1class Solution {
2 public int findNumbers(int[] nums) {
3 int eventDigits = 0;
4 for (int num : nums) {
5 if (hasEvenDigits(num)) {
6 eventDigits++;
7 }
8 }
9 return eventDigits;
10 }
11
12 private boolean hasEvenDigits(int num) {
13 int digits = 0;
14 while (num > 0) {
15 num = num / 10;
16 digits++;
17 }
18 return digits % 2 == 0;
19 }
20}


Comments