Adding Two Integers Without Using Arithmetic Operator

Hey guys!!! Welcome to flower brackets blog. In this post we are going to learn adding two integers without using arithmetic operator.

adding two integers without using arithmetic operator

To add two numbers without using arithmetic operators we will create addTwoNumbers() function. In this function we will not be using any arithmetic operators.

Example : adding two integers without using arithmetic operator

public class FB
{	
   static int addTwoNumbers(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("Addition of two numbers : " + addTwoNumbers(19, 26)); 
   }
}

Output:

Addition of two numbers : 45

 


Add two numbers without using arithmetic operators – recursive implementation

Here’s the code,

public class FB
{ 
   static int addTwoNumbers(int a,int b)
   { 
      if(b == 0) 
         return a; 
      else
         return addTwoNumbers(a ^ b, (a & b) << 1);
   }

   public static void main(String[] args) 
   { 
      System.out.println("Recursive implementation : " + addTwoNumbers(19, 26)); 
   }
}

Output:

Recursive implementation : 45


Subtract two numbers without using arithmetic operators

In the same lines as above, we are going to create subtractNumber() function and the function is executed without using any arithmetic operators. Here’s the code,

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

   public static void main(String[] args) 
   {
      int a = 26, b = 19; 
      System.out.println("Subtracting two numbers : " + subtractNumber(a, b)); 
   }
}

Output:

Subtracting two numbers : 7


Subtract two numbers without using arithmetic operators – recursive implementation

Here’s the code,

public class BitwiseAddition 
{ 
   static int subtractNumber(int a, int b) 
   {
      if(b == 0) 
         return a;
      return subtractNumber(a ^ b, (~a & b) << 1);
   }

   public static void main(String[] args) 
   {
      int a = 26, b = 19; 
      System.out.println("Recursive implementation : " + subtractNumber(a, b)); 
   }
}

Output:

Recursive implementation : 7


Conclusion

That’s it. So this is all about how to add two integers without using arithmetic operators in java. I hope you have understood the concept.

Do subscribe to my blog flower brackets if you haven’t already.

Do share this article if you like.

Related Posts