
1- If ‘K’ is negative, you have to perform left rotation. The bits that fall off at the left end are put back at the right end.
2- If ‘K’ is positive, you have to perform the right rotation. The bits that fall off at the right end are put back at the left end.
Consider If N = 13 and K = 2, then
Bits representation of N is 1101.
As K is greater than 0, we have to perform the right rotation
After the first rotation, bits representation will be 1110
After the second rotation, bits representation will be 0111
The integer value corresponding to ‘0111’ is 7. Hence the answer is 7.
The first line of the input contains an integer, 'T,’ denoting the number of test cases.
For each test case, there will be two space-separated integers, ‘N’ and ‘K’, denoting the given number and number of bitwise rotations you have to perform on ‘N’.
For each test, print a single integer representing the updated value of ‘N’ after ‘K’ bitwise rotations.
Print the output of each test case in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^12
-10^9 <= K <= 10^9
Time limit: 1 sec
In this approach, we will first calculate the number of bits in the bits representation of N and store that number as size. We will also store the MSB(Most Significant Bit) of N in a variable msb. For K times, we will shift the bits using a suitable bitwise shift operation on N (according to the sign of K). In the end, we will set N as N & (1<<(size) -1) to remove the extra bits and return the updated N.
In this approach, we will first calculate the number of bits in the bits representation of N and store that number as size. We will reduce K to K % size as we know rotating the bits any multiple of size times, we will get the initial bits representation.
For right rotation, we need to move the last K bits to the front, and the remaining size-K bits are shifted K times towards the right.
For left rotation, we need to move the first K bits to the end, and the remaining size-K bits are shifted K times towards the left.
We will use this observation to obtain the answer, and we will use bitwise shift operators to shift these bits.