Leetcode 1523. Count Odd Numbers in an Interval Range
Given two non-negative integers `low` and `high`. Return the count of odd numbers between `low` and `high` (inclusive).
Description
Given two non-negative integers low
and high
. Return the count of odd numbers between low
and high
(inclusive).
Example 1:
Input: low = 3, high = 7 Output: 3
- The odd numbers between 3 and 7 are [3,5,7].
Example 2:
Input: low = 8, high = 10 Output: 1
- The odd numbers between 8 and 10 are [9].
Constraints:
0 <= low <= high <= 10^9
Solution
1
2
3
4
5
6
7
class Solution:
# Mathematical Approach
# Time Complexity: BigO(1)
# Space Complexity: BigO(1)
def countOdds(self, low: int, high: int) -> int:
is_odd = 1 if high % 2 == 1 or low % 2 == 1 else 0
return (high - low)//2 + is_odd
//
: divide with integral result (discard remainder)
1
2
3
4
5
6
7
8
9
/**
* Mathematical Approach
* Time Complexity: BigO(1)
* Space Complexity: BigO(1)
*/
function countOdds(low: number, high: number): number {
let includes = high % 2 == 1 || low % 2 == 1 ? 1 : 0;
return Math.floor((high - low) / 2) + includes;
}
This post is licensed under CC BY 4.0 by the author.