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 addNumber() method which return sum of two integers.

In this method we will not be using any arithmetic operators instead we use XOR(^) of two bits. Here’s the program,

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


Above java program can be implemented for recursive approach. 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(addTwoNumbers(19, 26)); 
   }
}

Output:

45


Related Posts