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

后端 未结 22 1500
情书的邮戳
情书的邮戳 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:34

    In python using bitwise operators:

    def sum_no_arithmetic_operators(x,y):
        while True:
            carry = x & y
            x = x ^ y
            y = carry << 1
            if y == 0:
                break
        return x
    
    0 讨论(0)
  • 2020-11-27 05:34

    Here's a portable one-line ternary and recursive solution.

    int add(int x, int y) {
        return y == 0 ? x : add(x ^ y, (x & y) << 1);
    }
    
    0 讨论(0)
  • 2020-11-27 05:35

    Cheat. You could negate the number and subtract it from the first :)

    Failing that, look up how a binary adder works. :)

    EDIT: Ah, saw your comment after I posted.

    Details of binary addition are here.

    0 讨论(0)
  • 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);
      }
    
    0 讨论(0)
  • 2020-11-27 05:36

    You can do it using bit-shifting and the AND operation.

    #include <stdio.h>
    
    int main()
    {
        unsigned int x = 3, y = 1, sum, carry;
        sum = x ^ y; // Ex - OR x and y
        carry = x & y; // AND x and y
        while (carry != 0) {
            carry = carry << 1; // left shift the carry
            x = sum; // initialize x as sum
            y = carry; // initialize y as carry
            sum = x ^ y; // sum is calculated
            carry = x & y; /* carry is calculated, the loop condition is
                            evaluated and the process is repeated until
                            carry is equal to 0.
                            */
        }
        printf("%d\n", sum); // the program will print 4
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-27 05:37

    Define "best". Here's a python version:

    len(range(x)+range(y))
    

    The + performs list concatenation, not addition.

    0 讨论(0)
提交回复
热议问题