sum (adding 2 numbers ) without plus operator

后端 未结 9 660
借酒劲吻你
借酒劲吻你 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条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 21:21

    On a completely different note, perhaps what was being looked for was an understanding of how binary addition is done in hardware, with XOR, AND, and bit shifting. In other words, an algorithm something like this:

    int add(int a, int b)
    { int partial_sum = a ^ b;
      int carries = a & b;
    
      if (carries)
        return add(partial_sum, carries << 1);
      else
        return partial_sum;
    }
    

    Or an iterative equivalent (although, gcc, at least, recognizes the leaf function and optimizes the recursion into an iterative version anyway; probably other compilers would as well)....

    Probably needs a little more study for the negative cases, but this at least works for positive numbers.

提交回复
热议问题