What is the best way to add two numbers without using the + operator?

后端 未结 22 1665
情书的邮戳
情书的邮戳 2020-11-27 05:18

A friend and I are going back and forth with brain-teasers and I have no idea how to solve this one. My assumption is that it\'s possible with some bitwise operators, but n

22条回答
  •  渐次进展
    2020-11-27 05:35

    Here is the solution in C++, you can find it on my github here: https://github.com/CrispenGari/Add-Without-Integers-without-operators/blob/master/main.cpp

    int add(int a, int b){
       while(b!=0){
          int sum = a^b; // add without carrying
          int carry = (a&b)<<1; // carrying without adding
          a= sum;
          b= carry;
        }
       return a;
     }
     // the function can be writen as follows :
     int add(int a, int b){
         if(b==0){
            return a; // any number plus 0 = that number simple!
        }
        int sum = a ^ b;// adding without carrying;
        int carry = (a & b)<<1; // carry, without adding
        return add(sum, carry);
      }
    

提交回复
热议问题