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
Asked By: childoflogos

||

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)
Answered By: Noah
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
Answered By: Kool_Cool
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.