Swap bits

PROBLEM :

Given a number x and two positions (from right side) in binary representation of x, write a program that swaps n bits at given two positions and returns the result.

Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is X, P1, P2 and N. X is a number, P1 and P2 is two given position and swaps N number of bits at given two position.

Output:
Print the result.

Constraints:
1 = T = 15
1 = X = 200
0 = P1 < P2 = 8
1 = N = 5

Example:
Input:
2
47 1 5 3
28 0 3 2

Output:
227
7

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
int SwapBits(int ,int ,int ,int ) ;
int main()
{
int t ;
cin>>t ;
while(t--){
   int no,p1,p2,k ;
 
   cin>>no>>p1>>p2>>k ;
   cout<<SwapBits(no,p1,p2,k) ;
   cout<<endl ;
}
return 0;
}

int SwapBits(int no,int p1,int p2,int k){
    int set1,set2 ;
   
    set1=(no>>p1)&((1U<<k)-1) ;
    set2=(no>>p2)&((1U<<k)-1) ;
   
    int Xor=set1^set2 ;
    Xor=(Xor<<p1)|(Xor<<p2) ;
   
    return Xor^no ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )