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

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

    Java solution with bitwise operators:

    // Recursive solution
    public static int addR(int x, int y) {
    
        if (y == 0) return x;
        int sum = x ^ y; //SUM of two integer is X XOR Y
        int carry = (x & y) << 1;  //CARRY of two integer is X AND Y
        return addR(sum, carry);
    }
    
    //Iterative solution
    public static int addI(int x, int y) {
    
        while (y != 0) {
            int carry = (x & y); //CARRY is AND of two bits
            x = x ^ y; //SUM of two bits is X XOR Y
            y = carry << 1; //shifts carry to 1 bit to calculate sum
        }
        return x;
    }
    
    0 讨论(0)
  • 2020-11-27 05:50

    Why not just incremet the first number as often, as the second number?

    0 讨论(0)
  • 2020-11-27 05:50

    Adding two integers is not that difficult; there are many examples of binary addition online.

    A more challenging problem is floating point numbers! There's an example at http://pages.cs.wisc.edu/~smoler/x86text/lect.notes/arith.flpt.html

    0 讨论(0)
  • 2020-11-27 05:50

    Python codes: (1)

    add = lambda a,b : -(-a)-(-b)
    

    use lambda function with '-' operator

    (2)

    add= lambda a,b : len(list(map(lambda x:x,(i for i in range(-a,b)))))
    
    0 讨论(0)
提交回复
热议问题