Software Engineering

How to Add Two Integers Without Arithmetic Operator in Java


The challenge

Given two integers a, b, find The sum of them, BUT You are not allowed to use the operators + and –

Notes

  • The numbers (a,b) may be positive , negative values or zeros .
  • Returning value will be an integer .
  • Java: the following methods are prohibited: addExactaveragecollectdecrementincrementnextAfternextDownnextUpreducesubtractExactsumsumming .
    The following classes are prohibited: BigDecimal and BigInteger .

Examples

1- Add (5,19) ==> return (24) 
2- Add (-27,18) ==> return (-9)
3- Add (-14,-16) ==> return (-30)

The solution in Java code

Option 1:

public class Solution {
    public static int add(int x, int y) {
        if(y == 0) return x;
        int er = x ^ y;
        int ar = (x & y) << 1;
        return add(er, ar);
    }
}

Option 2:

import java.util.concurrent.atomic.AtomicInteger;
public class Solution {
    public static int add(int a, int b) {
        return (int)(new AtomicInteger(a)).addAndGet(b);
    }
}

Option 3:

public class Solution {
    public static int add(int x, int y) {
        return x \u002b y;
    }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SumTwoIntgers {
    @Test
    public void checkPositiveValues() {
        assertEquals( 3, Solution.add(1,2));
        assertEquals(24, Solution.add(5,19));
        assertEquals(40, Solution.add(23,17));
    }
    @Test
    public void checkNegativeValues() {
        assertEquals( -30, Solution.add(-14,-16));
        assertEquals(-226, Solution.add(-50,-176));
        assertEquals( -39, Solution.add(-10,-29));
    }
    @Test
    public void checkMixtureValues() {
        assertEquals(  0, Solution.add(-13,13));
        assertEquals( -9, Solution.add(-27,18));
        assertEquals(-60, Solution.add(-90,30));
    }
}