Home >Backend Development >C++ >Find the number with only set bits between Lth and Rth index using C++
In the given problem, we need to find the value of a number that has all 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
In the given problem, we will discuss two methods, brute force method and efficient method.
In this method we just iterate over the given range and add up all the powers of 2 in the given range and this will be our answer.
#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"; }
14
In this approach, we just iterate over the range and simply add the powers of 2 of the numbers in the range. The time complexity of this program is O(N), where N is the size of our range. But we can further improve the time complexity by applying bit knowledge in the given problem.
In this method we will simply construct a formula to calculate our answer.
#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"; }
14
In this method, we formulate a formula to calculate the answer.
As you know we need to count the numbers with set bits in the given range, so in this method we find a Bits are set to the number. We then need to subtract a number with all bits set from 1 to (L-1), so we formulate this observation. The overall time complexity of the given code is O(1), which is constant time complexity, which means we can compute any answer in constant time.
This article will write a program for "only numbers with set bits between L-th and R-th indexes". We also learned a C program and complete methods (common and efficient) to solve this problem. We can write the same program in other languages like C, Java, Python and others. Hope you find this article helpful.
The above is the detailed content of Find the number with only set bits between Lth and Rth index using C++. For more information, please follow other related articles on the PHP Chinese website!