Back to photostream

Count Odd Numbers in an Interval Range Leetcode Solution

Problem Statement

In this problem, we are given two non-negative integers low and high. We have to find how many odd numbers are there in the given interval range .

Example

low = 3, high = 7

3

Explanation:

 

The odd numbers between 3 and 7 are .

low = 8, high = 10

1

Explanation:

 

The odd numbers between 8 and 10 are .

Approach

One way to find the total count of odd numbers in the given interval range is to traverse from the left to right boundary of the interval in a loop and increase the odd counter for each odd number. But this will be a very lame approach for counting odd numbers in a range. This will take linear time complexity, and that we don't want for such an easy problem.

 

It is very easy to find total odd numbers in the given interval range as we know there are almost half even and half odd numbers in an interval range.

But we have to consider the interval boundaries very carefully. So what we can do is we can form the formula for the count of odd numbers in first n natural numbers. Let it be count. Then odd numbers between low and high will be equal to :

count = count - count.

 

Now taking some examples for count :

 

count=1

count=1

count=2

count=2

count=3

 

We can deduce that count = (n+1)/2

Hence count = (high+1)/2 - low/2

Implementation

C++ Program (Naive Approach) for Count Odd Numbers in an Interval Range Leetcode Solution

#include

using namespace std;

 

int countOdds(int low, int high)

{

int count=0;

for(int i=low;i

 

www.tutorialcup.com/leetcode-solutions/count-odd-numbers-...

11 views
0 faves
0 comments
Uploaded on September 14, 2021