How to Add Two Integers Without Arithmetic Operator in Java

1 min read 234 words

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));
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags