Leetcode 1295. Find Numbers with Even Number of Digits
Problem Statement
Given an array nums
of integers, return how many of them contain an even number of digits.
Clarifying Questions
- Input Size: What is the range of possible sizes for the input array?
- Assumption: The size of
nums
can range from 1 to 10,000.
- Element Range: What is the range of possible values for the elements in
nums
?
- Assumption: The elements in
nums
are positive integers.
- Output: Should the result be printed or returned?
- Assumption: The result should be returned as an integer.
Strategy
- Identify Even Number of Digits:
- To check if a number has an even number of digits, we can convert the number to a string and check the length of the string.
- Alternatively, we can use mathematical operations to count the digits without converting to a string.
- Counting the Valid Numbers:
- Iterate through each number in the array, check if it has an even number of digits, and maintain a count.
- Return the Count:
- Return the count after iterating through the array.
Code
#include <vector>
#include <cmath> // for log10
class Solution {
public:
int findNumbers(std::vector<int>& nums) {
int count = 0;
for (int num : nums) {
// Counting the number of digits without converting to string
int numDigits = std::floor(std::log10(num)) + 1;
if (numDigits % 2 == 0) {
count++;
}
}
return count;
}
};
Explanation
- Loop through Each Number:
- We iterate through each number in the array
nums
.
- Count Digits:
- Use
std::log10(num)
to find the number of digits: log10(num)
gives the number of digits minus one for a positive integer, so we add one to get the correct digit count.
- Check for Even Digits:
- If the number of digits is even (
numDigits % 2 == 0
), we increment our count.
- Return Result:
- Finally, return the count of numbers with an even number of digits.
Time Complexity
- O(n): We pass through the array exactly once, where
n
is the size of the array.
- Auxiliary Space: O(1): We use a fixed amount of extra space regardless of the input size.
Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI
-
Got blindsided by a question you didn’t expect?
-
Spend too much time studying?
-
Or simply don’t have the time to go over all 3000 questions?