You are given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).
Example 1:
Input: low = 2, high = 9
Output: 4Explanation: The odd numbers between 2 and 9 are [3,5,7,9].
Example 2:
Input: low = 9, high = 11
Output: 2Explanation: The odd numbers between 9 and 11 are [9,11].
Example 2:
Input: low = 1, high = 1
Output: 1Constraints:
0 <= low <= high <= 1,000,000,000Before attempting this problem, you should be comfortable with:
The simplest approach is to iterate through every number in the range and check if it is odd. We count all numbers where the least significant bit is 1.
low to high (inclusive).1.Where is the number of integers in the given range.
In any range of consecutive integers, odd and even numbers alternate. In a range of length n, there are n/2 odd numbers if n is even. If n is odd, the count depends on whether the range starts with an odd number. Starting with odd gives one extra odd number.
high - low + 1.length / 2.low) is odd, add 1 to include the extra odd.The count of odd numbers from 1 to n is (n + 1) / 2 (or equivalently (n + 1) >> 1). To find odd numbers in range [low, high], we take the count up to high and subtract the count below low. The count below low equals the count up to (low - 1), which is low / 2 or low >> 1.
1 to high: (high + 1) >> 1.1 to (low - 1): low >> 1.[low, high].When the range length is odd, whether you get an extra odd number depends on whether low (or high) is odd. Forgetting to check this boundary condition leads to undercounting by 1.
Simply computing (high - low) / 2 ignores whether the range starts or ends on an odd number. The formula must account for the parity of the boundaries, not just the length.