In this Leetcode Cyclic shifts problem solution, 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 if c = R.


HackerEarth Cyclic shifts problem solution


HackerEarth Cyclic shifts problem solution.

#include<bits/stdc++.h>
#define ll long long int
#define X 16
using namespace std;

ll checkL(ll n, ll m)
{
    ll val = (1<<m) - 1;
    int dif = X - m;

    val = val<<dif;


    ll front = n&val;


    front = front>>dif;


    val = (1<<dif) - 1;
    val = val&n;
    val = val<<m;

    return (val|front);
}

ll checkR(ll n, ll m)
{
    int dif = X - m;
    ll val = (1<<dif) - 1;
   

    val = val<<m;


    ll front = n&val;


    front = front>>m;


    val = (1<<m) - 1;
    val = val&n;
    val = val<<dif;

    return (val|front);
}

int main(){
    int t;
    cin>>t;
    assert(t >= 1 && t <= 10000);

    while(t--)
    {
        ll n,m;
        char ch;
        cin>>n>>m>>ch;
        assert(1 <= n && n <= 65535);
        assert(1 <= m && m <= 15);

        if(ch == 'R') cout<<checkR(n,m)<<endl;
        else cout<<checkL(n,m)<<endl;
    }
}

Second solution

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1.5e5 + 14;
int main(){
    ios::sync_with_stdio(0), cin.tie(0);
    int t;
    cin >> t;
    while(t--){
        int n, m;
        char d;
        cin >> n >> m >> d;
        string s = bitset<16>(n).to_string();
        m %= s.size();
        if(d == 'L')
            s = s.substr(m) + s.substr(0, m);
        else
            s = s.substr(s.size() - m) + s.substr(0, s.size() - m);
        cout << bitset<16> (s).to_ulong() << '\n';
    }
}