Sunday, August 8, 2010

Logical Error

Robin designed a logical circuit for adding two
numbers.
But he forgot to include the carry logic in his circuit. The
working of his faulty circuit for the case of adding two bits may be hence
defined as follows:
0 + 0 = 0
0 + 1 = 1
1 + 0 = 1
1 + 1 = 0



You are given two
integers, and you have to return the result as calculated by Robin's addition
circuit.



Input Specification



The input consists of multiple test cases. Each case
consists of two integers on separate lines. End of file denotes the end of
input.



Output Specification



For each test case output the result on a separate line.



Example Input





1

0



0



0



21



11



Example Output





1

0



30
The logic:
When a sum of 1+1 is taken as 0, an error of (2^n) is created in the sum, where n is the place (units, tens etc.) where the error is committed. Hence first calculate the correct sum by actual addition of the given two numbers. Then compute the error by examining the simultaneous occurrence of the bit 1 in the binary representation of the numbers.

#include<iostream>
using namespace std;
int main()
{
          int num1, num2, x , y ,i=-1 , sum1=0 ,sum=0 ,j ,z=1 ;  
          while(cin>>num1)
          {
                    cin>>num2;
                    i=-1 , sum1=0 ,sum=0 ,j=0 ,z=1;
                    //Adding the numbers for getting the correct sum.
                    sum=num1+num2;
                    do
                    {
                             z=1;
                             x = num1% 2;
                             ++i;
                             num1=num1/2;
                             y= num2% 2;
                             num2=num2/2;
                             //The condition where the bits  of both the numbers are 1.
                             if (x==1 && y == 1)
                            {
                                     //Computing the error at that place by multiplying 2, "the number of place" times. 
                                     for(j=0;j<=i;j++)
                                    {
                                             z*=2;
                                    }
                                    //Computing the total overall error.
                                    sum1+=z;
                           }
                   }while(num1!=0 && num2!=0);
                   //Subtracting the error from the correct sum.  
                   sum-=sum1;
                   cout<<sum<<endl;
         }
         return 0;  
}

1 comment: