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;
        return add(er, ar);
    }
}

Choice 2:

import java.util.concurrent.atomic.AtomicInteger;
public class Answer {
    public static int add(int a, int b) {
        return (int)(new AtomicInteger(a)).addAndGet(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() {
        assertEquals( 3, Answer.add(1,2));
        assertEquals(24, Answer.add(5,19));
        assertEquals(40, Answer.add(23,17));
    }
    @Check
    public void checkNegativeValues() {
        assertEquals( -30, Answer.add(-14,-16));
        assertEquals(-226, Answer.add(-50,-176));
        assertEquals( -39, Answer.add(-10,-29));
    }
    @Check
    public void checkMixtureValues() {
        assertEquals(  0, Answer.add(-13,13));
        assertEquals( -9, Answer.add(-27,18));
        assertEquals(-60, Answer.add(-90,30));
    }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments