Trusted answers to developer questions

Ravi

Consider a problem where we have to find the sum of two numbers without using the arithmetic operators `+`

, `-`

, `*`

, and `/`

.

Example 1:

- Input: 5, 8
- Output: 13

Example 2:

- Input: 5, -8
- Output: -3

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:

- Until there is no carry element, perform the below steps:
- Find the carry by performing AND (
`&`

) on`x`

and`y`

. - Find the sum by performing XOR (
`^`

) on`x`

and`y`

. The`x ^ y`

is assigned to .``. - The carry is left-shifted by one so that adding it to
`x`

gives the required sum. The left-shifted carry is assigned to`y`

.

- Find the carry by performing AND (
- Return
`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)); } }

- Lines 3–10: We define the
`iterative_add()`

method to implement the above solution iteratively. - Line 13: We define
`x.`

- Line 14: We define
`y`

. - Line 15: We invoke the
`iterative_add()`

method to calculate the sum of`x`

and`y`

. - Line 16: We print the sum.

RELATED TAGS

java

CONTRIBUTOR

Ravi

RELATED COURSES

View all Courses

Keep Exploring

Related Courses