Add two numbers without using arithmetic operators in java

In this post we are going to learn 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

In adding two integers without using arithmetic operators we will create addNumber() method which return sum of two integers.

Also read – java program to add two numbers

In this method we will not be using any arithmetic operators instead we use XOR(^) of two bits. Here’s the java program to add two numbers without using plus + or ++ arithmetic operator in java,

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


How to add two integers without arithmetic operator java example

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