ποΈ 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
- start num is
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);
};