Java Program to Add Two numbers Without using Arithmetic Operator
Last Updated :
20 Apr, 2023
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:
- Bit-wise XOR
- Bit-wise AND
- 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
import java.io.*;
class GFG {
static int Sum( int a, int b)
{
while (b != 0 ) {
int carry = a & b;
a = a ^ b;
b = carry << 1 ;
}
return a;
}
public static void main(String arg[])
{
System.out.println(Sum( 2 , 3 ));
}
}
|
Time Complexity: O(log2(b))
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...