Wednesday, February 21, 2024
HomeSoftware EngineeringHow you can Add Two Integers With out Arithmetic Operator in Java

# How you 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 optimistic , adverse values or zeros .
• Returning worth shall be an integer .
• Java: the next strategies are prohibited: addExactcommonaccumulatedecrementincrementnextAfternextDownnextUpcut 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;
}
}
``````

## Take a look at circumstances to validate our answer#

``````import org.junit.Take a look at;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SumTwoIntgers {
@Take a look at
public void checkPositiveValues() {
}
@Take a look at
public void checkNegativeValues() {
}
@Take a look at
public void checkMixtureValues() {
}
}
``````
RELATED ARTICLES