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.
1#include <iostream>
2#include <string>
3using namespace std;
4
5int findNumbers(vector<int>& nums) {
6 int count = 0;
7 for (int num : nums) {
8 if (to_string(num).length() % 2 == 0) {
9 count++;
10 }
11 }
12 return count;
13}
14
15int main() {
16 vector<int> nums = {12, 345, 2, 6, 7896};
17 cout << findNumbers(nums) << endl;
18 return 0;
19}
This C++ solution iterates through the vector of numbers, converts each number to a string to determine its length, and increments the count if the length 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
In Python, the math.log10()
function is used to determine the number of digits in a number. By flooring the result and adding 1, we get the digit count, which is checked for evenness.