Count Odd Numbers in an Interval Range
EASYDescription
Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).
Example 1:
Input: low = 3, high = 7 Output: 3 Explanation: The odd numbers between 3 and 7 are [3,5,7].
Example 2:
Input: low = 8, high = 10 Output: 1 Explanation: The odd numbers between 8 and 10 are [9].
Constraints:
0 <= low <= high <= 10^9
Approaches
Checkout 2 different approaches to solve Count Odd Numbers in an Interval Range. Click on different approaches to view the approach and algorithm in detail.
Brute Force Iteration
This approach involves iterating through each number in the given range from low to high. For each number, we perform a check to see if it is odd. A counter is maintained to keep track of the total count of odd numbers found.
Algorithm
- Initialize a counter variable
countto 0. - Loop through each integer
ifromlowtohigh(inclusive). - Inside the loop, check if
iis odd using the modulo operator (i % 2 != 0). - If
iis odd, incrementcount. - After the loop finishes, return
count.
The algorithm is very straightforward:
- Initialize a counter variable,
count, to zero. - Create a loop that iterates from
lowtohigh, inclusive. - Inside the loop, for each number
i, use the modulo operator (%) to check if it's odd (i % 2 != 0). - If the number is odd, increment the
count. - After the loop completes, the
countvariable will hold the total number of odd integers in the range, which is then returned.
Here is the Java implementation:
class Solution {
public int countOdds(int low, int high) {
int count = 0;
for (int i = low; i <= high; i++) {
if (i % 2 != 0) {
count++;
}
}
return count;
}
}
Complexity Analysis
Pros and Cons
- Very simple to understand and implement.
- Works correctly for small ranges.
- Highly inefficient for large ranges.
- Will not pass the time constraints on most competitive programming platforms for this problem due to the large constraints (up to 10^9).
Code Solutions
Checking out 3 solutions in different languages for Count Odd Numbers in an Interval Range. Click on different languages to view the code.
class Solution { public int countOdds ( int low , int high ) { return (( high + 1 ) >> 1 ) - ( low >> 1 ); } }Video Solution
Watch the video walkthrough for Count Odd Numbers in an Interval Range
Similar Questions
5 related questions you might find useful
Patterns:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.