Given two non-negative integers low and high, count how many odd numbers fall between them,
inclusive. (LeetCode 1528)
Key observations:
- Odd numbers satisfy
n % 2 == 1. - We need to count all odd numbers in
[low, high], including the boundaries if they’re odd. - Odd numbers occur every other number, so roughly half of any range is odd.
Approach: the number of integers between low and high is high - low + 1. If both
boundaries are odd, the count increases by one (since both are included); if only one is odd, the
basic pattern holds; if both are even, the count is exactly half the range size.
class Solution { public int countOdds(int low, int high) { // Calculate the difference between high and low int result = high - low;
// If the result (range) is even and high is odd, we can count (result/2) + 1 odd numbers if(result % 2 == 0 && high % 2 == 1){ return result / 2 + 1; } // If the result is odd, we also have (result / 2) + 1 odd numbers else if(result % 2 == 1){ return result / 2 + 1; } // In all other cases, return result / 2 else{ return result / 2; } }}For low = 3, high = 7: range [3,4,5,6,7], odd numbers [3,5,7] → output 3. For
low = 8, high = 10: range [8,9,10], odd number [9] → output 1.
This solution runs in O(1) since it’s based on simple arithmetic calculations.