I calculate how many odd numbers appear up to high and subtract how many appear up to low - 1. Any number x has (x + 1) // 2 odd numbers from 0 to x, so the total odds in the range is simply (high + 1) // 2 - (low // 2).
class Solution:
def countOdds(self, low: int, high: int) -> int:
length = high - low + 1
ans = length // 2
if low % 2 == 1 and high % 2 == 1:
ans += 1
return ans- Time:
- Space: