Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created December 7, 2025 17:27
Show Gist options
  • Select an option

  • Save tatsuyax25/500dedbe65c3f232f5574652fdaee207 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/500dedbe65c3f232f5574652fdaee207 to your computer and use it in GitHub Desktop.
Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).
/**
* @param {number} low
* @param {number} high
* @return {number}
*/
var countOdds = function(low, high) {
// Step 1: Think about what we want:
// We need to count how many odd numbers exist between low and high (inclusive).
// Step 2: Use math instead of looping:
// Formula: floor((high + 1) / 2) - floor(low / 2)
// Why? Because:
// - floor(x / 2) gives the count of even numbers up to x.
// - floor((x + 1) / 2) gives the count of odd numbers up to x.
// Subtracting gives us the count of odds in the range [low, high].
// Step 3: Apply the formula
let countHigh = Math.floor((high + 1) / 2); // odds from 0 up to high
let countLow = Math.floor(low / 2); // odds from 0 up to (low - 1)
// Step 4: Subtract to get odds in [low, high]
return countHigh - countLow;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment