GeeksforGeeks » Interview Questions

Microsoft Interview Question for Software Engineer/Developer (Fresher) about Bit Magic

(8 posts)
  • Started 7 months ago by batman
  • Latest reply from Aashish Barnwal

Tags:

  1. batman
    guest
    Posted 7 months ago #

    given a 32-bit integer x. find the smallest integer x0 > x with the same number of ones in binary representation

    Example:
    x = 76
    x0 = 81

  2. urrohit
    Member
    Posted 7 months ago #

    start from the lsb ... get the first 1 in the in its binary representation & exchange with the next bit .. if there r 2 2 or more consecutive 1s then move the last one one position ahead n place the first one in the 0th position

  3. pgiitu
    Member
    Posted 7 months ago #

    Convert the first number in the binary. Start iterating from the LSB and get the first 1. exchange it with the next higher bit if the bit is zero else if there are more than 2 1's together move the most significant a place ahead and rest 1's to the least significant bit end.

    For Ex

    x =101101
    x0=101110 just move the first 1 on LSB.

    x = 1011100
    x0 =1100011 move the 1 at index 4 starting from LSB to index 5 and rest all to the LSB end

  4. anurag kumar
    guest
    Posted 7 months ago #

    1) while(!(bit_at[i]==1 && bit_at[i+1]==0)) \\i=lsb position
    { i++; if(i==31 )break;}
    if(i==31) printf("given number is the largest number possible ")
    else { bit_at[i]=0;bit_At[i+1]=1; }

    if(i-1 <0 || bit_at[i-1]==0 )return;
    else {start=i-1;
    end=0;
    while(start<end)
    {
    while(start<end && bit_at[start]!=1) start--
    while(start<end && bit_at[end]!=0) end++
    bit_At[start]==0;bit_At[end]==1;

    }

    }

  5. Hackme
    Member
    Posted 6 months ago #

    int i=0,c,k;
    while(bitArray[i++]==0){
        if(i==31) return;
    }
    c=i;
    while(bitArray[i++]==1){
        if(i==31) return;
    }
    bitArray[i]=1;
    for(k=0;k<i;k++){
        if(k<(i-c-1)){
            a[k]=1;
        }
        else    a[k]=0;
    }
    
  6. wolfwood
    Member
    Posted 6 months ago #

    input: x
    output: z

    y = (x | (x - 1)) + 1
    z = y | ((((y & -y) / (x & -x)) >> 1) - 1);

  7. Shantanu
    guest
    Posted 5 months ago #

    int b=1;
    int bit;
    bool doIt = false;
    
    for(int i = 1; i<= 32; i++)
    {
    	bit = num & b;
    	if( bit == 0 && doIt == false )
    	{
    		b = b << 1;
    
    		continue;
    	}
    	if( bit != 0 && doIt == false )
    	{
    
    		doIt = true;
    		b = b << 1;
    
    		continue;
    	}
    	if( bit != 0 )
    	{
    		b = b << 1;
    		continue;
    	}
    	num = num | b;
    	b = b >> 1;
    	b = ~b;
    	num = num & b;
    	break;
    }
    return num;
    
  8. Dedicated Programmer
    Member
    Posted 1 month ago #

    1) first=x&(~x)
    2) second=x+first
    3) third=x^second
    4) fourth=(third>>2)/first
    5) result=second | fourth


Reply

You must log in to post.

RSS feed for this topic