Skip to content
Related Articles

Related Articles

Cyclic shifts of integer N by another integer m

View Discussion
Improve Article
Save Article
  • Last Updated : 26 Nov, 2021
View Discussion
Improve Article
Save Article

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.
Examples:
 

Input : N = 7881, m = 5, c = L 
Output : 55587 
Explanation: 
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 
Explanation: 
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. 
 

 

Approach:
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:
 

C++




// C++ implementation of the approach
#include<bits/stdc++.h>
using namespace std;
 
// Cyclic shifts of integer N by another integer m
void Count(int N, int m, char turn)
{
  // str represents bitwise representation of N
  string str = bitset<16>(N).to_string();
   
  m%=(int)str.size();
   
  // rotate the string by a specific count
  if(turn=='R')
    str = str.substr((int)str.size()-m) + str.substr(0,(int)str.size());
  else 
    str = str.substr(m) + str.substr(0,m);
   
  // printing the number represented by the bitset
  // in str
  cout << bitset<16> (str).to_ulong() << '\n';
}
 
int main()
{
  int N = 7881 ;
  int m = 5;
  char turn = 'L';
  Count(N,m,turn);
}

Python3




# 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)])
         
    else:
        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)

Output: 

55587

 

Time Complexity: O(n)

Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!