Skip to content
RSS feed tkhwang on GitHub tkhwang on Twitter

πŸ€– leetcode 1523. Count Odd Numbers in an Interval Range | easy | math | javascript

πŸ—’οΈ Problems

Count Odd Numbers in an Interval Range - LeetCode

Given two non-negative integers low and high.
Return the count of odd numbers between low and high (inclusive).
Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].

πŸ€” First attempt

I thought that the answer depends on the given interval length.

  • odd :
  • even :
    • start num is odd
    • start num is even
var countOdds = function (low, high) {
  const len = high - low + 1;

  if (len % 2 === 0) return Math.floor(len / 2);

  return low % 2 === 0 ? Math.floor(len / 2) : Math.floor(len / 2) + 1;
};

Hmm... not good enough.

πŸ₯³ Think differently

  • Can I use the prefixSum style calculation ?
1     2     3      4      5      6      7      8      9
                 [low           high]
[1                              high]  = count(hight)
*           *             *
[1       low-1]                        = count(low - 1)
*           *

πŸ€ Template

πŸ’‘ count(num)

  • [1...num] : Math.floor((num + 1)/2)
1     2     3      4      5      6      7      8      9
*           *
                  num               => 1,3    = Math.floor((4 + 1)/2)
*           *             *
                         num        => 1,3,5  = Math.floor((5 + 1)/2)

πŸ”₯ My Solution

/**
 * @param {number} low
 * @param {number} high
 * @return {number}
 */
var countOdds = function (low, high) {
  const count = (num) => Math.floor((num + 1) / 2);

  return count(high) - count(low - 1);
};