Leetcode 1523. Count Odd Numbers in an Interval Range
You are 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].
Input
: low = 8
, high = 10
Output
: 1
Explanation: The odd number between 8 and 10 is [9].
low
and high
always valid inputs such that low <= high
?
low
and high
inclusive in the range?
Assuming no other constraints or conditions are provided. Let’s move on to the strategy and code.
To count the number of odd numbers between low
and high
inclusive:
high
.low - 1
.low
and high
inclusive.n
, the count of odd numbers from 1 to n
inclusive is (n + 1) // 2
.high
: (high + 1) // 2
low - 1
: low // 2
Therefore, the count of odd numbers between low
and high
inclusive:
[ \text{count_odds} = \left(\frac{high + 1}{2}\right) - \left(\frac{low}{2}\right) ]
#include <iostream>
int countOdds(int low, int high) {
// Calculate the number of odd numbers up to high and low-1
int odds_up_to_high = (high + 1) / 2;
int odds_up_to_low_minus_one = low / 2;
// The difference will give the result
return odds_up_to_high - odds_up_to_low_minus_one;
}
int main() {
// Example test cases
std::cout << countOdds(3, 7) << std::endl; // Output: 3
std::cout << countOdds(8, 10) << std::endl; // Output: 1
return 0;
}
The time complexity of the solution is O(1)
(constant time) because the computations involved are basic arithmetic operations that take constant time regardless of the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?