JAVA
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Based on Ace's answer to chavan dipak dattatray's question:
// https://www.sololearn.com/Discuss/1107912
// Write program addition of two numbers don't use (+ plus)operator
import java.util.Random;
public class Program {
private static Random rand = new Random();
// Recursive add with argument debug so you can see
// what it is doing. When y is zero, x has the
// answer. Otherwise, an exclusive OR of the two
// numbers adds all the bits without conflict while
// the AND shifted takes care of the overflows for
// all the matching 1 bits. These overflows still
// need to be added into the result so we recurse.
// 3+4=7
// 11, 100 yields 11^100 is 111 plus 11&100<<1
// is 0. Recursives with 111, 0. Exits out with
// 111.
// 2+2=4
// 10, 10 yields 10^10 or 0 plus 10&10<<1 is 10<<1
// is 100. Recursives with 0, 100. 0^100 is 100
// 0&100<<1 is 0. Recursives with 100, 0. Exits
// out with 100.
static int add(int x, int y) {
System.out.printf("%d(%s), %d(%s)\n",
x, Integer.toBinaryString(x),
y, Integer.toBinaryString(y));
return (y != 0)?add(x^y, (x&y)<<1):x;
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run