sum (adding 2 numbers ) without plus operator

后端 未结 9 661
借酒劲吻你
借酒劲吻你 2021-02-05 20:42

Can anyone explain the logic how to add a and b?

#include 

int main()
{
     int a=30000, b=20, sum;
     char *p;
             


        
9条回答
  •  -上瘾入骨i
    2021-02-05 21:15

    /*
    by sch.
    
    001010101 = 85
    001000111 = 71
    ---------
    010011100 = 156
    */
    
    #include 
    
    #define SET_N_BIT(i,sum) ((1 << (i)) | (sum))
    
    int sum(int a, int b)
    {
        int t = 0;
        int i = 0;
        int ia = 0, ib = 0;
        int sum = 0;
        int mask = 0;
    
        for(i = 0; i < sizeof(int) * 8; i++)
        {   
            mask = 1 << i;
            ia = a & mask;
            ib = b & mask;
    
            if(ia & ib)
                if(t)
                {
                    sum = SET_N_BIT(i,sum);
                    t = 1;
                    /*i(1) t=1*/
                }
                else
                {
                    t = 1;
                    /*i(0) t=1*/
                }
            else if (ia | ib)
                if(t)
                {
                    t = 1;
                    /*i(0) t=1*/
                }
                else
                {
                    sum = SET_N_BIT(i,sum);
                    t = 0;
                    /*i(1) t=0*/
                }
            else
                if(t)
                {
                    sum = SET_N_BIT(i,sum);
                    t = 0;
                    /*i(1) t=0*/
                }
                else
                {
                    t = 0;
                    /*i(0) t=0*/
                }
    
        }
    
        return sum;
    }
    
    int main()
    {
        int a = 85;
        int b = 71;
        int i = 0;
    
        while(1)
        {
            scanf("%d %d", &a, &b);
    
            printf("%d: %d + %d = %d\n", ++i, a, b, sum(a, b));
        }
    
        return 0;
    }
    

提交回复
热议问题