703317. Digits in a set
Counting the Numbers 2359
Slug: count-the-numbers2359
Difficulty: Easy
Id: 703317
Topic Tags: Arrays, Data Structures
Company Tags: Morgan Stanley
Summary
The problem is about counting the numbers from a given set that contain the digits 2, 3, 5, or 9. The problem does not specify the range of numbers, but we can assume it's within a reasonable range (e.g., 0 to 10000). This problem involves basic array manipulation and counting.
Detailed Explanation
The algorithmic approach is straightforward. We iterate through each number in the set and check if it contains any of the digits 2, 3, 5, or 9. If a number contains one or more of these digits, we increment our count. This process continues until all numbers have been processed.
Here's a step-by-step breakdown:
- Initialize a counter variable to zero.
- Iterate through each number in the set.
- For each number, check if it contains any of the digits 2, 3, 5, or 9 using the modulo operator (
%). For example,num % 10gives us the last digit of the number. - If a number contains one or more of these digits, increment our counter variable.
- Repeat steps 2-4 until all numbers have been processed.
Time complexity: O(n), where n is the size of the input set. Space complexity: O(1), since we only use a constant amount of space to store the counter variable.
Optimized Solutions
Java
public class CountNumbers2359 {
public static int countNumbers(int[] numbers) {
int count = 0;
for (int num : numbers) {
if ((num % 10000 >= 200000 || num % 10000 <= 299999) &&
(num % 10 == 2 || num % 10 == 3 || num % 10 == 5 || num % 10 == 9)) {
count++;
}
}
return count;
}
}