Java Program to Add Two numbers Without using Arithmetic Operator
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 operator then there is only one way out that 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 in 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:
Input : 1, 2 Output : 3
a = 1 : 00000001 b = 2 : 00000010 ---------------- c = 3 : 00000011
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.