Skip to content
Related Articles

Related Articles

Improve Article

Cyclic shifts of integer N by another integer m

  • Last Updated : 27 Aug, 2020

Given an integer N represented as a binary representation of X = 16 bits. We are also given a number ‘m’ and a character c which is either L or R. The task is to determine a number M that is generated after cyclically shifting the binary representation of N by m positions either left if c = L or right if c = R.


Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input : N = 7881, m = 5, c = L
Output : 55587
N in binary is 0001 1110 1100 1001 and shifting it left by 5 positions, it becomes 1101 1001 0010 0011 which in the decimal system is 55587.

Input : N = 7881, m = 3, c = R
Output : 9177
N in binary is 0001 1110 1100 1001 and shifted 3 positions to right, it becomes 0010 0011 1101 1001 which in the decimal system is 9177.


To solve the problem mentioned above we observe that we have to right shift the number by m if the char is R, else we will do a left shift by m if the char is L where left shifts is equivalent to multiplying a number by 2, right shifts is equivalent to dividing a number by 2.

Below is the implementation of the above approach:

# Python implementation to make 
# Cyclic shifts of integer N by another integer m
def Count(N, count, turn):
    # Convert N into hexadecimal number and
    # remove the initial zeros in it
    N = hex(int(N)).split('x')[-1]
    # Convert hexadecimal term binary
    # string of length = 16 with padded 0s
    S = ( bin(int(N, 16))[2:] ).zfill(16)
    # rotate the string by a specific count
    if(turn == 'R'):
        S = (S[16 - int(count) : ] + S[0 : 16 - int(count)])
        S = (S[int(count) : ] + S[0 : int(count)])
    # Convert the rotated binary string
    # in decimal form, here 2 means in binary form.
    print(int(S, 2))
# driver code 
N = 7881
count = 5
turn = 'L'
Count(N, count, turn)

My Personal Notes arrow_drop_up
Recommended Articles
Page :