GeeksforGeeks » Interview Questions
In any given number, how to swap two consequtive bits
(4 posts)-
Consider a number whose binary representation is : 10110010.
To represent it more clearly if represented as pairs of two bits the number would be : 10-11-00-10
After Swappiing the result should be : 01-11-00-01.Please provide a generic solution which could be valid for a number of any size(1 byte, 2byte, 4 byte)
-
n is the no to be changed.
count=0;
num=0;
while(n>0)
{
t1=n&1;
n=n>>1;
t2=n&1;
n=n>>1;t3=0;
t3=t3|t1;
t3=t3<<1;
t3=t3|t2;t3=t3<<count;
count+=2;
num=num|t3;}
printf("\n%d",num);
-
let the no in a;
b= a | 01 01 01 01 (in binary)
c = a | 10 10 10 10(in binary)
b<<1;
c>>1;
add b and c = output -
int main() { int n,k,i,bit1,bit2; printf("Enter n "); scanf("%d",&n); k=n; i=0; while(k) { if(bit1=(n&(1<<i))) n&=~(1<<i); if(bit2=(n&(1<<(i+1)))) n&=~(1<<(i+1)); if(bit1 && bit2) { n|=(1<<i); n|=(1<<(i+1)); } else if(bit1) n|=1<<(i+1); else if(bit2) n|=1<<i; i+=2; k>>=2; } printf("%d",n); return 0; }Let me know if there is any better approach
Reply
You must log in to post.