Count Odd Numbers in an Interval Range. Leetcode problem №1523. Python
Question:
I tried to solve this problem from leetcode and I came up with the following code but the testcase where low = 3 and high = 7 gives 2 as an output and 3 is expected by leetcode. I will be grateful if you explain what is wrong and how it should be done.
class Solution:
def countOdds(self, low: int, high: int) -> int:
count = 0
for i in range(low, high):
if i % 2 != 0:
count += 1
return count
Answers:
range(low, high)
will result in a range of (low, low+1, low+2, …, high -1). Meaning that in your case high will not be considered.
If high should also be considered use:
range(low, high + 1)
class Solution:
def countOdds(self, low: int, high: int) -> int:
# lst = [ num for num in range(low , high+1) if num%2!=0]
# return len(lst)
# brut force doesnt gona work
# it works but it nearly take 15 seconds
# very high
#case 1 => both odd
if low%2!=0 and high%2!=0:
return int((high - low)/2) + 1
#case 2 => both even
if low%2==0 and high%2==0:
#division is always float
return int((high -low)/2)
# case 3 => either one of them is even and other is odd
if (low%2==0 and high%2!=0 ) or (low%2!=0 and high%2==0):
return int((high - low)/2)+1
I tried to solve this problem from leetcode and I came up with the following code but the testcase where low = 3 and high = 7 gives 2 as an output and 3 is expected by leetcode. I will be grateful if you explain what is wrong and how it should be done.
class Solution:
def countOdds(self, low: int, high: int) -> int:
count = 0
for i in range(low, high):
if i % 2 != 0:
count += 1
return count
range(low, high)
will result in a range of (low, low+1, low+2, …, high -1). Meaning that in your case high will not be considered.
If high should also be considered use:
range(low, high + 1)
class Solution:
def countOdds(self, low: int, high: int) -> int:
# lst = [ num for num in range(low , high+1) if num%2!=0]
# return len(lst)
# brut force doesnt gona work
# it works but it nearly take 15 seconds
# very high
#case 1 => both odd
if low%2!=0 and high%2!=0:
return int((high - low)/2) + 1
#case 2 => both even
if low%2==0 and high%2==0:
#division is always float
return int((high -low)/2)
# case 3 => either one of them is even and other is odd
if (low%2==0 and high%2!=0 ) or (low%2!=0 and high%2==0):
return int((high - low)/2)+1