Count Odd Numbers in an Interval Range
The problem asks to return the count of odd numbers between two given non-negative integers low
and high
(inclusive).
Approach
To count the number of odd numbers between low
and high
, we can use the following observations:
- If both
low
andhigh
are even, then the number of odd numbers between them will be(high - low) / 2
. - If one of
low
orhigh
is odd, then the number of odd numbers between them will be(high - low) / 2 + 1
.
Combining the two cases, we can write the following function:
|
|
This code takes into account both cases by adding 1 to high
before dividing by 2 and then subtracting low
divided by 2.
Example
For low = 3
and high = 7
, the odd numbers between them are [3, 5, 7]
, so the output is 3
.
For low = 8
and high = 10
, the odd numbers between them are [9]
, so the output is 1
.
Complexity
This solution has a time complexity of O(1) and a space complexity of O(1), as it involves only simple arithmetic operations.
|
|