Given an array nums
of integers, return how many of them contain an even number of digits.
1 <= nums.length <= 500
1 <= nums[i] <= 105
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.
We can solve this coding problem by iterating through nums array and counting number of digits in each number. If number of digits in each number is even, increase ans by 1 else continue the loop.
C++ implementation of above solution is as follows.
class Solution {
public:
int findNumbers(vector<int>& nums) {
int n = nums.size();
int ans = 0;
for(int i=0; i<n; i++) {
int x = nums[i];
int digitCount = 0;
while(x > 0) {
x = x/10;
digitCount += 1;
}
if(digitCount % 2 == 0) {
ans += 1;
}
}
return ans;
}
};
O(n)
where n = number of elements in nums array.
O(1) since we are not using any additional space.
Thanks for reading and have a nice day.