Given two positive integers n and k, perform a circular shift on the binary representation of n by k positions.

The circular shift can be of two types:

  1. Left circular shift (moving the final bit to the first position while shifting all other bits to the next position).
  2. Right circular shift (moving the first bit to the last position while shifting all other bits to the previous position).

 
For example,

Input:
 
N = 127        (00000000000000000000000001111111)
shift = 3
 
Output:
 
Left Shift     00000000000000000000001111111000
Right Shift    11100000000000000000000000001111

Practice this problem

The idea is to perform a normal bitwise left or right shift by first isolating the sequence of k–bits from the right or left side, respectively. Finally, return the bitwise OR of the shifted number with isolated bits at their correct position.

For example, consider n = 127 which is 00000000000000000000000001111111.

Circular Right shift by 3:

1. Isolate the 3–bits from the right:
 
00000000000000000000000001111111
 
 
2. Right shift by 3
 
00000000000000000000000001111111
00000000000000000000000000001111
 
 
3. OR with isolated bits:
 
00000000000000000000000000001111
11100000000000000000000000000000
————————————————————————————————
11100000000000000000000000001111

Circular Left shift by 3:

1. Isolate the 3–bits from the left:
 
00000000000000000000000001111111
 
 
2. Left shift by 3:
 
00000000000000000000000001111111
00000000000000000000001111111000
 
 
3. OR with isolated bits:
 
00000000000000000000001111111000
00000000000000000000000000000000
————————————————————————————————
00000000000000000000001111111000

Following is the C++ and Java program that demonstrates it:

C++


Download  Run Code

Java


Download  Run Code

Output:
 
No Shift    00000000000000000000000001111111
Left Shift  00000000000000000000001111111000
Right Shift 11100000000000000000000000001111