1523. Count Odd Numbers in an Interval Range

The idea of this solution is to get the number odd numbers from 0 to high, and then subtract the number of odd numbers from 0 to low - 1. The idea can be shown by an example:


high: 7
low : 3

image

  • The odd numbers from 0 to high (7). There are 4 odd numbers from 0 to 7.

image

  • The odd numbers from 0 to low - 1 (2). There is 1 odd numbers from 0 to 2.

The number of odd numbers would be 4 - 1 = 3. Three odd numbers.


func countOdds(low int, high int) int {
	return (high + 1)/2 - low / 2
}