Norway


Given a positive n and k, perform circular on of it by k positions.


 

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 =

Output:
Left Shift  000000000000000000000011111100
Right Shift 11100000000000000000000000001111
 

 
The idea is to perform a normal bitwise left or right shift by first isolating the sequence of k-bits from the right side or left side respectively. Finally return the bitwise OR of 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

 
C++ implementation –
 

Download   Run Code

Output:

No Shift    00000000000000000000000001111111
Left Shift  00000000000000000000001111111000
Right Shift 11100000000000000000000000001111

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here