Header Ads Widget

Cyclic shifts

Problem:-

You are given a number N represented as a binary representation of X=16 bits. You are also given a number m and a character c (L or R).
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 is c=R.
Input format 
  1. The first line contains an integer T representing the number of queries.
  2. The next T lines contain N m c as mentioned in the problem statement.
Output format
Print T integers in a separate line representing the answer to each query.
Constraints
1T1e41N655351m15
 
SAMPLE INPUT
 
2
7881 5 L
7881 3 R
SAMPLE OUTPUT
 
55587
9177
Explanation
For first case :  N in binary is 0001 1110 1100 1001 and shifting it left by 5 position, it becomes 1101 1001 0010 0011 which in decimal system is 55587

For second case : N in binary is 0001 1110 1100 1001 and shifted 3 position to right it becomes 0010 0011 1101 1001 which in decimal system is 9177
Time Limit:1.0 sec(s) for each input file.
Memory Limit:256 MB
Source Limit:1024 KB

solution:-

#include<stdio.h>
#include<math.h>
void main()
{
     int t,i,m,x,a[16],b[16],j=0,d[16],p;
     char c,c1;
     long int n,s=0;
     scanf("%d",&t);
     for(i=1;i<=t;i++)
     {
         for(j=0;j<16;j++)
          a[j]=0;
         scanf("%ld%d%c%c",&n,&m,&c,&c1);
         j=0;
         while(n!=0)
         {
            x=n%2;
            n=n/2;
            a[j]=x;
            j++;
         }
         for(j=0;j<16;j++)
         b[j]=a[15-j];
         if(c1=='R')
         {
            for(j=15;j>=0;j--)
            {
             if((j-m)>=0)
             d[j]=b[(j-m)];
             else
            {
                 d[j]=b[(j-m)+16];
            }
            }
         }   
         if(c1=='L')
         {
         for(j=0;j<16;j++)
         d[j]=b[(j+m)%16];
         }
         p=15;
         for(j=0;j<16;j++)
         {
            s=s+d[j]*pow(2,p);
            p--;
         }
         printf("%ld\n",s);
         s=0;
     }
}

Post a Comment

0 Comments