Monday, 9 March 2015

Flipping bits

Problem Statement
You will be given a list of 32 bits unsigned integers. You are required to output the list of the unsigned integers you get by flipping bits in its binary representation (i.e. unset bits must be set, and set bits must be unset).
Input Format
The first line of the input contains the list size T, which is followed by Tlines, each line having an integer from the list.
Constraints
1T100
0integer<232
Output Format
Output one line per element from the list with the requested result.
Sample Input
3 
2147483647 
1 
0
Sample Output
2147483648 
4294967294 
4294967295
Explanation
Take 1 for example, as unsigned 32-bits is 00000000000000000000000000000001 and doing the flipping we get 11111111111111111111111111111110 which in turn is 4294967294.

/*Code by Sudhakar Pandey */
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main()
 {
   int i,size,res=0;
   scanf("%d",&size);
   unsigned int arr[size];
   for(i=0;i<size;i++)
        scanf("%u",&arr[i]);
   for(i=0;i<size;i++)
     flippingbits(arr[i]);
       
 return 0;
}

void flippingbits(int n)
 {
        
    int  c, k;
    int arr[32]={0};
    int i,j=0,temp;
    int arr2[32]={0};
    unsigned int decimal=0;
  
   for (c = 31; c >=0; c--)
    {
       k = n >> c;

      if (k & 1)
      {
         arr[c]=1;     
     }
    else
      {
 arr[c]=0;
     
     }
  }

  
   for(i=31;i>=0;i--)
    {
      if(arr[i]==1)
       arr[i]=0;
     else 
      {  
        if(arr[i]==0)
    arr[i]=1;
      }
   }

   for(i=31,j=0;i>=0;i--,j++)
    arr2[j]=arr[i];

    
   for(i=31,j=0;i>=0;i--,j++)
       decimal=decimal+(arr2[i] *pow(2,j) ) ;
        
    
     printf("%u\n",decimal); 
}

No comments:

Post a Comment