GeeksforGeeks » Interview Questions

In any given number, how to swap two consequtive bits

(4 posts)
  • Started 7 months ago by abhi4eternity
  • Latest reply from Guddu Sharma

Tags:

  1. abhi4eternity
    Member
    Posted 7 months ago #

    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)

  2. Anil Purohit
    guest
    Posted 7 months ago #

    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);

  3. gaurav
    guest
    Posted 7 months ago #

    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

  4. Guddu Sharma
    Member
    Posted 1 month ago #

    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.

RSS feed for this topic