Consider a problem where we have to find the sum of two numbers without using the arithmetic operators +
, -
, *
, and /
.
Example 1:
Example 2:
In half adder logic, we can add two bits by performing their XOR (^
), the sum bit. We can obtain the carry bit by performing AND (&
) of two bits.
We can apply the same logic to obtain the sum of two numbers.
The steps of the algorithm are as follows:
&
) on x
and y
.^
) on x
and y
. The x ^ y
is assigned to .``.x
gives the required sum. The left-shifted carry is assigned to y
.x
as the sum will be x
.public class Main {static int iterative_add(int x, int y) {while(y != 0){int carry = x & y;x = x ^ y;y = carry << 1;}return x;}public static void main(String[] args) {int x = 10;int y = 15;int sum = iterative_add(x, y);System.out.println(String.format("(Iterative sum) %d + %d = %d", x, y, sum));}}
iterative_add()
method to implement the above solution iteratively.x.
y
.iterative_add()
method to calculate the sum of x
and y
.