Sunday, February 25, 2024
HomeSoftware EngineeringHow one can Add Two Integers With out Arithmetic Operator in Java

# How one can Add Two Integers With out Arithmetic Operator in Java

## The problem#

Given two integers a, b, discover The sum of them, BUT You aren’t allowed to make use of the operators + and –

Notes

• The numbers (a,b) could also be constructive , adverse values or zeros .
• Returning worth shall be an integer .
• Java: the next strategies are prohibited: addExactcommonacquiredecrementincrementnextAfternextDownnextUpscale backsubtractExactsumsumming .
The next courses 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 answer in Java code#

Choice 1:

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

Choice 2:

``````import java.util.concurrent.atomic.AtomicInteger;
public static int add(int a, int b) {
}
}
``````

Choice 3:

``````public class Answer {
public static int add(int x, int y) {
return x u002b y;
}
}
``````

## Check instances to validate our answer#

``````import org.junit.Check;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SumTwoIntgers {
@Check
public void checkPositiveValues() {
}
@Check
public void checkNegativeValues() {
}
@Check
public void checkMixtureValues() {
}
}
``````
RELATED ARTICLES