Adding Two Integers Without Using Arithmetic Operator

Sharing is healthy !!

In this post we are going to learn adding two integers without using arithmetic operator.

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

The following program demonstrates the example,

Example: adding two integers without using arithmetic operator

Also Read РAddition Program in Java

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

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 adding two integers without using arithmetic operator.

I hope you have understood the concept very well. Do subscribe to my blog flower brackets if you haven’t already.

Do share this post if you like.

Sharing is healthy !!

Leave a Reply

Your email address will not be published.