
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case will contain two integers ‘N’ and ‘K’ where ‘N’ denotes the number whose 0 to ‘K’th bits have to be set and ‘K’ indicates the limit upto where from 0th bit, the bits have to be set.
For each test case, print the number after 0 to Kth bits are set.
Output for every test case will be printed in a separate line.
You don’t need to print anything; It has already been taken care of.
Can you solve this using O(1) time and space complexity?
1 <= T <= 10
-10^9 <= N <= 10^9
1 <= K <= 31
Time limit: 1 sec
The basic idea is to iterate through each bit from 0 till Kth bit and manually set each of the bits irrespective of whether they are set or not. At each index ‘i’ in the iteration manually set each bit and update the number ‘N’ by performing the Bitwise OR of the number ‘N’ with the set bit i.e. (1<<’i’). At last, after iterating, return the number ‘N’.
Here is the algorithm:
The basic idea of this approach is to perform the action of just making a set only 1 bit. What we were doing in the brute force method was setting every bit till less than ‘K’. So it is similar to just set the ‘K’th bit and subtracting that by 1. ( For example, 7(0111) = 8(1000) - 1), Here K=3). Store this integer in variable ‘temp’. Now just perform the Bitwise OR of the number ‘N’ with ‘temp’ and store it in ‘N’. Thus by this way the number ‘N’ is updated with each of the bit from 0 to ‘K’ as set. At last, return ‘N’.
Here is the algorithm: