
If ‘N’ = 12 and ‘K’ = 2:
The binary representation of 12 is ‘1100’, after toggling rightmost 2 bits, it becomes ‘1111’ i.e. 15. Hence, the answer is 15.
The first line contains a single integer T representing the number of test cases.
The first and only line of each test case contains two space-separated integers ‘N’ and ‘K’ that represent the given 32-bit integer and number of rightmost bits to toggle respectively.
For each test case, return the new Integer after toggling the rightmost ‘K’ bits.
You don’t need to print anything, it has already been taken care of. Just implement the given function
Can you solve this using O(1) time complexity?
1 <= T <= 10
1 <= N <= 10^9
1 <= K <= 31
Time Limit: 1 sec
The idea is to simply iterate through the rightmost ‘K’ bits and toggle them one by one using the XOR operator.
Here is the algorithm:
The idea is to first extract the rightmost ‘K’ and toggle them. Then, after clearing the rightmost ‘K’ bits from the original integer, storing the toggled bits back into the original integer.
Here is the algorithm: