Open In App

Java Program to Add Two numbers Without using Arithmetic Operator

Last Updated : 20 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Here, we need to write a function that returns the sum of two stated integers. And the function must not utilize any of the arithmetic operators such as +, ++, –, -, .. Etc.). It will be a very basic elementary level program to compute the sum by simply using the ‘+’ operator and thereby simply printing and displaying out the resultant. But if we refrain from constraint not to use any of arithmetic operators then there is only one way out which is with the use of XOR operator which can perform an addition operation for two given bits. And for the carry bit, we can use AND (&) operator.

It is done using the bit-wise operators. Here we are going to use mainly three operations as follows:

  1. Bit-wise XOR
  2. Bit-wise AND
  3. Bit-wise left shift operator

First, the numbers are converted into binary format. Considering 8 indices for an integer data type.  Now the carry is handled by a bit-wise left shift operator and the rest of the binary is displayed on the screen as an integer number depicting the sum of the above two integers. It is depicted below: 

Example:

Input  : 1, 2
Output : 3
Explanation: 
a = 1 : 00000001
b = 2 : 00000010
—————-
c = 3 : 00000011 

Implementation:

Java




// Java Program to find the Sum of Two Numbers
// Without Using any Arithmetic Operator
 
// Importing input output classes
import java.io.*;
 
// Main class
class GFG {
 
    // Method to sum two integer elements
    static int Sum(int a, int b)
    {
 
        // Iterating until there is no carry
        while (b != 0) {
 
            // Using AND operator
            int carry = a & b;
 
            // Using XOR operator
            a = a ^ b;
 
            // Shifting the carry by one so that
            // adding it to the integer 'a'
            // gives the desired output
            b = carry << 1;
        }
        return a;
    }
 
    // Method 2
    // Main driver method
    public static void main(String arg[])
    {
 
        // Print the sum of custom integer numbers to be
        // summed up passed as an arguments
        System.out.println(Sum(2, 3));
    }
}


Output

5

Time Complexity: O(log2(b))
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads