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 <stdio.h>
2#include <string.h>
3
4int findNumbers(int* nums, int numsSize) {
5 int count = 0;
6 for (int i = 0; i < numsSize; i++) {
7 char str[10];
8 sprintf(str, "%d", nums[i]);
9 if (strlen(str) % 2 == 0) {
10 count++;
11 }
12 }
13 return count;
14}
15
16int main() {
17 int nums[] = {12, 345, 2, 6, 7896};
18 int size = sizeof(nums) / sizeof(nums[0]);
19 printf("%d\n", findNumbers(nums, size));
20 return 0;
21}
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.
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#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int findNumbers(vector<int>& nums) {
int count = 0;
for (int num : nums) {
if (static_cast<int>(log10(num)) % 2 == 1) {
count++;
}
}
return count;
}
int main() {
vector<int> nums = {12, 345, 2, 6, 7896};
cout << findNumbers(nums) << endl;
return 0;
}
In this C++ code, log10()
is used to determine the number of digits. Adding 1 to static_cast
gives the digit count, which is checked for evenness.