알고리즘
Find Numbers with Even Number of Digits
짬뽕얼큰하게
2025. 4. 30. 20:31
Leetcode Problem:
Summary
- Count numbers with even number of digits in an array
Approach
- The approach used is to iterate through each number in the array and calculate the number of digits in each number using a helper function
- If the number of digits is even, it increments the counter
- Finally, it returns the count of numbers with even number of digits.
Complexity
- O(n * log(max_num)) where n is the size of the array and max_num is the maximum number in the array
Explanation
- The solution iterates through each number in the array
- For each number, it calculates the number of digits using a helper function
- If the number of digits is even, it increments the counter
- The time complexity of the helper function is O(log(max_num)) and it is called for each number in the array
- Therefore, the overall time complexity is O(n * log(max_num)) where n is the size of the array and max_num is the maximum number in the array.
Solution Code:
class Solution {
public:
int getDigitNum(int num){
int cnt = 0;
while(num){
num/=10;
cnt++;
}
return cnt;
}
int findNumbers(vector& nums) {
int ans = 0;
for(int num : nums){
if(getDigitNum(num) % 2){
continue;
}
ans++;
}
return ans;
}
};
class Solution {
public:
int getDigitNum(int num){
int cnt = 0;
while(num){
num/=10;
cnt++;
}
return cnt;
}
int findNumbers(vector& nums) {
int ans = 0;
for(int num : nums){
if(getDigitNum(num) % 2){
continue;
}
ans++;
}
return ans;
}
};