Add two numbers without using arithmetic operators in java

Let’s learn to add two numbers without using arithmetic operators in java.

add two numbers without using arithmetic operators in java

Add two numbers without using arithmetic operators in java

To add two numbers without using arithmetic operators create addNumber() method which return sum of two integers.

Also read – continue statement in java

In addNumber() method we will not be using any arithmetic operators. Instead we are using bitwise operator XOR(^) of two bits.

Now let’s see java program to add two number without using arithmetic operator,

public class FB
{ 
   static int addNumber(int a, int b) 
   {
      while(b != 0) 
      { 
         int carry = a & b; 
         a = a ^ b; 
         b = carry << 1; 
      }
      return a;
   }

   public static void main(String[] args) 
   {
      System.out.println(addNumber(25, 25));
   }
}



Output:

50


Similarly we can subtract two numbers without using arithmetic operators.

Here we write static int method/function to subtract two numbers which return subtraction of two integers without using arithmetic operator.

To subtract two numbers without using arithmetic operators we use subtractor logic. So truth table for half subtractor is,

Input Output
A B Difference Borrow
0 0 0 0
0 1 1 1
1 0 1 0
1 1 0 0

Here is the java program to subtract two numbers without using arithmetic operator,

public class SubtractDemo 
{
   static int subtractNumber(int i, int j) 
   { 
      while(j != 0) 
      { 
         int carry = (~i) & j; 
         i = i ^ j; 
         j = carry << 1; 
      }
      return i;
   }
	
   public static void main(String[] args) 
   {
      int a = 23, b = 10;
      System.out.println("a - b is " + subtractNumber(a, b));
   }
}


Output:

a – b is 13

Also we can multiply two numbers without using arithmetic operators. Unlike above java program we make use of recursive function like this,

public class MultiplyDemo 
{
   static int multiplyNumber(int a, int b) 
   {    
      // 0 multiplied with 0 is 0
      if(b == 0) 
         return 0;

      // adding a one by one
      if(b > 0) 
         return (a + multiplyNumber(a, b - 1));

      // here's the case where b is negative
      if(b < 0) 
         return -multiplyNumber(a, -b); 

      return -1; 
   } 
   public static void main(String[] args) 
   {
      System.out.print(multiplyNumber(6, -10));
   }
}


Output:

-60