Problem Description
Given two non-negative integers low and high, count the number of odd numbers between low and high (inclusive).
Key Insights
- The range is inclusive of both endpoints.
- Instead of iterating through the range, we can use mathematical properties of integers.
- Half of the integers up to any number are odd. Use integer division to count odds.
- Compute the odds up to high and subtract the odds up to (low - 1).
Space and Time Complexity
Time Complexity: O(1) Space Complexity: O(1)
Solution
The idea is to count the number of odd numbers from 1 to high and subtract the number of odd numbers from 1 to (low - 1). The formula to count odd numbers up to a given number n is n // 2 if n is even, and (n // 2 + 1) if n is odd. This can be simplified into a single formula: (n + 1) // 2. So, the result is given by (high + 1) // 2 - (low) // 2.
- Data Structures Used: Only integers and arithmetic operations.
- Algorithmic Approach: Mathematical formula based on integer division. No iteration over the range.
- Mental Leap: Realizing that calculating odds up to a number allows direct computation avoiding explicit loop iteration, making it efficient.