Algorithms – Addition without using arithmetic operators like +, ++ or Math methods

To perform addition without using + or ++ (or java.lang.Math class which internally uses +), we will have to perform addition using logical operators. To understand how addition works using logical operators, we will have to take it at binary level.

Lets try addition of 25 & 15 which should result in 40. We will first convert 25 & 15 into binary.

x = 25 = 00011001

y = 15 = 00001111

Manual addition of binary numbers

As we all know, manually addition of binary on paper is done using below rules.

Rules:

Assembly (x86)

1

2

3

4

5

0+0=0,carry0

0+1=1,carry0

1+0=1,carry0

1+1=0,carry1

Special:1+1+1=(1+1)+1=(0,carry1)+1=1,carry1

Addition of 25 & 15 in binary: Add digits right to left using above rules, Add carry to left digit. Consider carry in addition of next left digit & use same rules again & so on.

Assembly (x86)

1

2

3

4

5

6

7

00111110<--Carry

---------------

00011001<--25

+

00001111<--15

----------------

00101000<--40

Do this programmatically

Now if you look at rules, you might find some similarity with the truth tables of some logical operations.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Rules:

0+0=0,carry0

0+1=1,carry0

1+0=1,carry0

1+1=0,carry1

Thisissimilar toXORtruth table

0+0=0

0+1=1

1+0=1

1+1=0

Thisissimilar toANDtruth table.

0+0=carry0

0+1=carry0

1+0=carry0

1+1=carry1

So basically XOR can tell us the addition of digit without carry & AND operator can tell us carry. There’s one slight catch here. Carry is supposed to be added in earlier/left digit, so basically once you figure out carry, you will have to shift left by 1 position to actually use carry in addition.