Sunday, February 26, 2023
HomeSoftware EngineeringThe best way to Add Two Integers With out Arithmetic Operator in...

The best way to 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: addExactcommongatherdecrementincrementnextAfternextDownnextUpscale backsubtractExactsumsumming .
    The next lessons 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

Possibility 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);
    }
}

Possibility 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);
    }
}

Possibility 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() {
        assertEquals( 3, Answer.add(1,2));
        assertEquals(24, Answer.add(5,19));
        assertEquals(40, Answer.add(23,17));
    }
    @Take a look at
    public void checkNegativeValues() {
        assertEquals( -30, Answer.add(-14,-16));
        assertEquals(-226, Answer.add(-50,-176));
        assertEquals( -39, Answer.add(-10,-29));
    }
    @Take a look at
    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