Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created December 7, 2025 23:00
Show Gist options
  • Select an option

  • Save Ifihan/ded1d855d47612f440701d020574c15d to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/ded1d855d47612f440701d020574c15d to your computer and use it in GitHub Desktop.
Count Odd Numbers in an Interval Range

Question

Approach

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).

Implementation

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

Complexities

  • Time:
  • Space:
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment