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

后端 未结 22 1705
情书的邮戳
情书的邮戳 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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;
    }
    

提交回复
热议问题