# Find the number with set bits only between L-th and R-th index using C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In the given problem we need to find the value of a number which has all of the set bits between the given range L, R. For example −

Input: L = 1, R = 5
Output: 62
Explanation: representation of given L and R in binary form is 0..0111110

Input: L = 1, R = 4
Output: 30
Explanation: representation of given L and R in binary form is 0..11110

## Approach to find The Solution

In the given problem, we are going to discuss two approaches, Brute Force and Efficient Approach.

## Brute Force

In this approach, we are simply going to traverse through the given range and add all the power of 2 in the given range, and that will be our answer.

## Example

#include<bits/stdc++.h>
using namespace std;
int main() {
int L = 1, R = 3; // the given range
int ans = 0; // our answer
for(int i = L; i <= R; i++) // traversing through the whole range
ans += pow(2, i); // adding values to the answer.
cout << ans << "\n";
}

## Output

14

In this approach, we are simply traversing through the range and simply adding the power of 2 of the numbers in the range. This program has a time complexity of O(N), where N is the size of our range. But we can further improve the time complexity by applying knowledge of bits in the given question.

## Efficient Approach

In this approach, we will simply make up a formula that will calculate our answer for us.

## Example

#include<bits/stdc++.h>
using namespace std;
int main() {
int L = 1, R = 3; // the given range
int ans = 0; // our answer
for(int i = L; i <= R; i++) // traversing through the whole range
ans += pow(2, i); // adding values to the answer.
cout << ans << "\n";
}

## Output

14

In this approach, we make a formula for calculating our answer.

## Explanation of the above code

As you know, we need to calculate the number with set bits in the given range, so in this approach, we find a number that has all its bits set till R from 0. Then we need to subtract a number that has all the bits set from 1 till (L-1), and thus we formulate this observation. The overall time complexity of the given code is O(1) which is constant time complexity which means we can calculate any answer in constant time.

## Conclusion

This article will make a program for “Number with set bits only between L-th and R-the index.”We also learned the C++ program for this problem and the complete approach ( Normal and efficient ) by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this article helpful.