Given Q queries, with each query consisting of two integers L and R, the task is to find the total numbers between L and R (Both inclusive), having atmost three set bits in their binary representation.
Input : Q = 2 L = 3, R = 7 L = 10, R = 16 Output : 5 6 For the first query, valid numbers are 3, 4, 5, 6, and 7. For the second query, valid numbers are 10, 11, 12, 13, 14 and 16.
Method 1 (Simple): A naive approach is to traverse all the numbers between L and R and find the number of set bits in each of those numbers. Increment a counter variable if a number does not have more than 3 set bits. Return answer as counter. Note : This approach is very inefficient since the numbers L and R may have large values (upto 1018).
Method 2 (Efficient) : An efficient approach required here is precomputation. Since the values of L and R lie within the range [0, 1018] (both inclusive), thus their binary representation can have at most 60 bits. Now, since the valid numbers are those having atmost 3 set bits, find them by generating all bit sequences of 60 bits with less than or equal to 3 set bits. This can be done by fixing, ith, jth and kth bits for all i, j, k from (0, 60). Once, all the valid numbers are generated in sorted order, apply binary search to find the count of those numbers that lie within the given range.
Below is the implementation of above approach.
Time Complexity : O((Maximum Number of Bits)3 + Q * logN), where Q is the number of queries and N is the size of set containing all valid numbers. l valid numbers.
- Modular exponentiation (Recursive)
- Sum of XOR of sum of all pairs in an array
- nth Rational number in Calkin-Wilf sequence
- Bitwise OR (or | ) of a range
- Check whether the number has only first and last bits set | Set 2
- The painter's partition problem
- Bits manipulation (Important tactics)
- How to swap two numbers without using a temporary variable?
- Swap all odd and even bits
- Count set bits in an integer
- Number of values of b such that a = b + (a^b)
- Check if elements of Linked List are present in pair
- Find triplets in an array whose AND is maximum
- Set the rightmost off bit
- Length of longest consecutive zeroes in the binary representation of a number.
This article is contributed by Team GeeksforGeeks. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.