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

Since we are not using arithmetic operators in the below example, addTwoNumbers function is used.

Also Read – Bitwise Addition

The following program demonstrates the example on how to add using bitwise operators,

Example: adding two integers without using arithmetic operator

import java.util.Scanner;

public class BitwiseAddition
{
   static int addTwoNumbers(int a, int b)
   {
      int carryNum;

      while(b ! =  0)
      {
         carryNum = a & b;
         a = a ^ b;
         b = carryNum << 1;
      }
      return a;
   }

   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter numbers to be added: ");

      int a = sc.nextInt(); // Scans the next token of the input as an int.
      int b = sc.nextInt(); // Scans the next token of the input as an int.

      System.out.println("The output is: " + addTwoNumbers(a, b));
      sc.close();
   }
}

Output:

adding two integers without using arithmetic operator


Using recursion

Here let’s see how to add two integers without using arithmetic operators in java using recursion method,

import java.util.Scanner;

public class BitwiseAddDemo
{
   static int addTwoNumbers(int a, int b)
   {
      if (b == 0)
      return a;

      int total = a ^ b;
      int carryNum = (a & b) << 1;
      return addTwoNumbers(total, carryNum);
   }

   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter numbers to be added : ");

      int a = sc.nextInt();
      int b = sc.nextInt();

      System.out.println("The output is: " + addTwoNumbers(a,b));
      sc.close();
   }
}

Output:

Please enter numbers to be added : 10 40
The output is: 50


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 of add two numbers without using + operator.

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

Do share this article if you like.

Related Posts