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:

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.

Do this programmatically

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

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.

0 0 1 0 1 0 0 0 = 40 (Which is correct sum of 25 + 15)

Java Code to achieve this

Below Java code achieves exact same steps shown above using Bitwise XOR (^), Bitwise AND (&) & Left Shift (<<) operator.

 

 

 

 

 

 

Leave a Reply

Your email address will not be published.