Java simple easy understand solution with explanation
I have been confused about bit manipulation for a very long time. So I decide to do a summary about it here.\n\n"&" AND operation, for example, 2 (0010) & 7 (01
I have been confused about bit manipulation for a very long time. So I decide to do a summary about it here.\n\n"&" AND operation, for example, 2 (0010) & 7 (0111) => 2 (0010)\n\n"^" XOR operation, for example, 2 (0010) ^ 7 (0111) => 5 (0101)\n\n"~" NOT operation, for example, ~2(0010) => -3 (1101) what??? Don't get frustrated here. It's called two's complement.\n\n1111 is -1, in two's complement\n\n1110 is -2, which is ~2 + 1, ~0010 => 1101, 1101 + 1 = 1110 => 2 \n\n1101 is -3, which is ~3 + 1\n\nso if you want to get a negative number, you can simply do ~x + 1\n\nReference:\n\n[https://en.wikipedia.org/wiki/Two%27s_complement][1]\n\n[https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html][2]\n\nFor this, problem, for example, we have a = 1, b = 3,\n\nIn bit representation, a = 0001, b = 0011,\n\nFirst, we can use "and"("&") operation between a and b to find a carry.\n\ncarry = a & b, then carry = 0001\n\nSecond, we can use "xor" ("^") operation between a and b to find the different bit, and assign it to a, \n\nThen, we shift carry one position left and assign it to b, b = 0010.\n\nIterate until there is no carry (or b == 0)\n\n    // Iterative\n    public int getSum(int a, int b) {\n\t\tif (a == 0) return b;\n\t\tif (b == 0) return a;\n\n\t\twhile (b != 0) {\n\t\t\tint carry = a & b;\n\t\t\ta = a ^ b;\n\t\t\tb = carry << 1;\n\t\t}\n\t\t\n\t\treturn a;\n    }\n\n    // Iterative\n    public int getSubtract(int a, int b) {\n\t\twhile (b != 0) {\n\t\t\tint borrow = (~a) & b;\n\t\t\ta = a ^ b;\n\t\t\tb = borrow << 1;\n\t\t}\n\t\t\n\t\treturn a;\n\t}\n\n    // Recursive\n\tpublic int getSum(int a, int b) {\n\t\treturn (b == 0) ? a : getSum(a ^ b, (a & b) << 1);\n\t}\n\n\t// Recursive\n\tpublic int getSubtract(int a, int b) {\n\t\treturn (b == 0) ? a : getSubtract(a ^ b, (~a & b) << 1);\n\t}\n\t\n\t// Get negative number\n\tpublic int negate(int x) {\n\t\treturn ~x + 1;\n\t}\n\n\n  [1]: https://en.wikipedia.org/wiki/Two%27s_complement\n  [2]: https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html
['Java']