Similar Problems
Similar Problems not available
Count Odd Numbers In An Interval Range - Leetcode Solution
Companies:
LeetCode: Count Odd Numbers In An Interval Range Leetcode Solution
Difficulty: Easy
Topics: math
Problem Statement:
Given two non-negative integers low
and high
, return the count of odd numbers between low
and high
(inclusive).
Example:
Input: low = 3, high = 7 Output: 3 Explanation: The odd numbers between 3 and 7 are 3, 5, and 7.
Approach:
We can loop over all numbers between low
and high
, check if a number is odd, and count the number of odd numbers. However, this approach will be very inefficient for large ranges of numbers. Therefore, we need to find a more efficient approach.
One way to solve this problem efficiently is to first check if low
and high
are odd or even. If both numbers are even, then there are no odd numbers in the range. If both numbers are odd, then the count of odd numbers is equal to (high-low)/2 + 1
. If one number is odd and the other is even, then the count of odd numbers is equal to (high-low+1)/2
.
Solution:
We can implement the above approach in a function as follows:
class Solution:
def countOdds(self, low: int, high: int) -> int:
if low % 2 == 0 and high % 2 == 0:
return 0
elif low % 2 == 1 and high % 2 == 1:
return (high-low)//2 + 1
else:
return (high-low+1)//2
In this function, we first check if both low
and high
are even. If they are, we return 0 as there are no odd numbers in the range. If both numbers are odd, we count the number of odd numbers using the formula (high-low)//2 + 1
. If one number is odd and the other is even, we count the number of odd numbers using the formula (high-low+1)//2
.
Testing:
We can test our function using the example provided in the problem statement:
s = Solution()
low = 3
high = 7
result = s.countOdds(low, high)
print(result)
The output of the above code should be 3
, which is the correct answer.
Count Odd Numbers In An Interval Range Solution Code
1