
You are given two integers, ‘N’ and ‘K’ .Your task is to bitwise rotate the given integer ‘N’, ‘K’ number of times. The Bit Rotation is an operation similar to shift except that the bits that fall off at one end are put back to the other end.
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.
For example:
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’.
Output Format:
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.
Note:
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
2
13 2
12 -2
7
3
For the first test case,
Bits representation for N = 13 will be 1101.
After K = 2 right rotations, Bits representation will be 0111.
The integer value corresponding to ‘0111’ is 7. Hence the answer is 7.
For the second test case,
Bits representation for N = 12 will be 1100.
After K = 2 left rotations, Bits representation will be 0011.
The integer value corresponding to ‘0011’ is 3. Hence the answer is 3.
2
21 3
5 -3
22
5
Try to use bitwise shift operators.
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.
Algorithm:
O(log(N) + K), where N is the given number and K is the number of bitwise rotations to be performed.
The time complexity O(log(N)) is used to find the total number of bits in the given number. All bitwise operation takes O(1) time. We are doing shifting operations K times. Hence the overall time complexity is O(log(N) + K).
O(1).
We are using constant space. Hence the overall space complexity is O(1).